package com.example.switchyard.docs; import org.switchyard.component.bean.Service; @Service(Example.class) public class ExampleBean implements Example { }
The Bean Component is a pluggable container in SwitchYard which allows Java classes (or beans) to provide and consume services. This means that you can implement a service by simply annotating a Java class. It also means you can consume a service by injecting a reference to that service directly into your Java class. Rather than writing our own POJO container to provide this capability, we have implemented the bean component as a Weld extension. No need to learn a new programming model - bean services are standard CDI beans with a few extra annotations. This also opens up the possibilities of how SwitchYard is used; you can now expose existing CDI-based beans in your application as services to the outside world or consume services within your bean
To create a new Bean service you only need a few pieces of information:
Name : the name of the Java class for your bean service.
Service Name : the name of the service your bean will provide.
Interface : the contract for the service being provided. Java is the only valid interface type for bean services.
Note that starting with the interface value will default the names for Name and Service Name, which can speed things up if you're in a hurry.
After clicking Finish, you will have a new class that looks something like this:
package com.example.switchyard.docs; import org.switchyard.component.bean.Service; @Service(Example.class) public class ExampleBean implements Example { }
The @Service annotation allows the SwitchYard CDI Extension to discover your bean at runtime and register it as a service. The value of the annotation (Example.class in the above example) represents the service contract for the service. Every bean service must have an @Service annotation with a value identifying the service interface for the service.
To complete the definition of your service, add one or more operations to the service interface and provide a corresponding implementation in your bean:
package com.example.switchyard.docs; import org.switchyard.component.bean.Service; @Service(Example.class) public class ExampleBean implements Example { public void greet(Person person) { // implement service logic here for greet operation } }
In addition to providing a service in SwitchYard, beans can also consume other services. These services can be provided in the same application by other implementations, or they could be wired to gateway bindings to invoke services over JMS, SOAP, FTP, etc. The SwitchYard runtime handles the resolution of the service reference to a concrete service, allowing your service logic to remain blissfully ignorant. Invocations made through this reference are routed through the SwitchYard exchange mechanism.
Consuming a SwitchYard service from within a CDI bean is done via @Reference annotations.
@Service(ConsumerService.class) public class ConsumerServiceBean implements ConsumerService { @Inject @Reference private SimpleService service; public void consumeSomeService(String consumerName) { service.sayHello("Hello " + consumerName); } }
By default, SwitchYard expects a service reference to be declared with a name which matches the Java type used for the reference. In the above example, the SimpleService type would require a service reference in your SwitchYard configuration called "SimpleService". In the event where the service reference name is different from the type name of the contract, the @Reference annotation can accept a service name:
@Reference("urn:myservices:purchasing:OrderService") private OrderService orders;
While it's a best practice to write your service logic to the data that's defined in the contract (the input and output message types), there can be situations where you need to access contextual information like message headers (e.g. received file name) in your implementation. To facilitate this, the Bean component allows you to access the SwitchYard Exchange Context instance associated with a given Bean Service Operation invocation. To get a reference to the Context, simply add a Context property to your bean and annotate it with the CDI @Inject annotation.
@Service(SimpleService.class) public class SimpleServiceBean implements SimpleService { @Inject private Context context; public String sayHello(String message) { System.out.println("*** Funky Context Property Value: " + context.getPropertyValue("funkyContextProperty")); return "Hi there!!"; } }
The Context interface allows your bean logic to get and set properties in the context. Note that you can only make calls on the Context instance within the scope of one of the Service Operation methods. Invoking it outside this scope will result in an UnsupportedOperationException being thrown.
In contrast to invocation properties, implementation properties represent environmental properties that you have defined in the SwitchYard application descriptor (switchyard.xml) for your bean implementation. To access these properties, simply add an @Property annotation to your bean class identifying the property you want to inject. The following example demonstrates injection of a "user.name" property:
@Service(SimpleService.class) public class SimpleServiceBean implements SimpleService { @Property(name="user.name") private String name; public String sayHello(String message) { return "Hello " + name + ", I got a message: " + message; } }
See the Properties section of the User Guide for more information about SwitchYard property support.
Camel services allow you to leverage the core routing engine inside of Apache Camel to route between services in SwitchYard. All of the EIP and core routing support in Camel is available to your service implementation. Each Camel route is exposed as a service within SwitchYard, which means it has a well-defined contract and can be injected into any other service in the runtime.
The first thing you need to decide when you create a Camel routing service is whether you want to use the Java DSL or XML dialect for the route. Functionally, they are more or less equivalent, so it's more a choice of how you want to express your routing logic. If you want create a Java DSL route, select the "Camel (Java)" implementation type. For XML, use the "Camel (XML)" type. Regardless of which language you choose, the following information is required:
Name : the name of the Java class or XML file for your bean service.
Service Name : the name of the service your bean will provide.
Interface : the contract for the service being provided. Camel supports Java, WSDL, and ESB contract types.
For details on each type of Camel route, see the Java DSL Routes and XML Routes sections below. You can have multiple routing services per application, each with it's own routing language (e.g. an application can have two Java DSL routes and one XML route). There are some general guidelines to keep in mind with both types of routes:
There is only one route per service.
The consumer or "from" endpoint in a route is always a "switchyard" endpoint and the endpoint name must equal the service name. This is default behavior in the tooling.
To consume other services from within your route, only use "switchyard" consumer (i.e. "to") endpoints. This keeps your routing logic independent of the binding details for consumed services.
A newly created Java DSL route looks like this:
package com.example.switchyard.docs; import org.apache.camel.builder.RouteBuilder; public class CamelServiceRoute extends RouteBuilder { /** * The Camel route is configured via this method. The from: * endpoint is required to be a SwitchYard service. */ public void configure() { // TODO Auto-generated method stub from("switchyard://Example").log( "Received message for 'Example' : ${body}"); } }
There are no SwitchYard-specific classes or APIs used for Java DSL routes; the route class is identical in signature to what you would use with Apache Camel directly. Since there is one route per service, you will have one RouteBuilder class for each Camel routing service in your application. To add logic to your routing service, simply add additional logic to the configure() method. For background and details on what you can do with the Java DSL, please consult the Apache Camel documentation.
A newly created XML route looks like this:
<?xml version="1.0" encoding="ASCII"?> <route xmlns="http://camel.apache.org/schema/spring"> <from uri="switchyard://Example"/> <log message="Example - message received: ${body}"/> </route>
Like Java DSL routes, the XML routing syntax is identical to what you would use with Apache Camel directly and conforms to the Camel schema for <route> definitions. There will be one file containing a route definition for each XML routing service in your application.
Invoking another service from within your Camel route can be done by using the SwitchYard producer endpoint (switchyard://) within your route. Endpoint configuration is very straightforward:
switchyard://[service-name]?operationName=[operation-name]
service-name : name of the SwitchYard service. This value needs to match the name of a service reference defined on the service component for the route.
operation-name : name of the service operation to be invoked. This is only used on references and is optional if the target service only has a single operation.
A modified version of the default XML route which invokes a SwitchYard service can be found below:
<?xml version="1.0" encoding="ASCII"?> <route xmlns="http://camel.apache.org/schema/spring"> <from uri="switchyard://Example"/> <log message="Example - message received: ${body}"/> <!-- Invoke hasItem operation on WarehouseService --> <to uri="switchyard://WarehouseService?operationName=hasItem"/> </route>
Camel supports dynamic languages inside route logic in both XML and Java form. As the support for dynamic languages is built in JDK any language which provides javax.script.ScriptEngineManager may be used. However, because of 3rd party dependencies by default SwitchYard supports only following languages:
BeanShell
JavaScript
Groovy
Ruby
Python
To use these script languages you have couple of options. They are available in expression-aware places like filter:
public class ScriptingBuilder extends RouteBuilder { public void configure() { from("switchyard://Inbound") .filter().javaScript("request.getHeader('myHeader') != null") .to("switchyard://Outbound"); } }
If you would like use dynamic language to implement your service you may use transform element:
public class ScriptingImplementationBuilder extends RouteBuilder { public void configure() { from("switchyard://Inbound") .transform().groovy("classpath:script.groovy"); // classpath resource from("switchyard://InboundBsh") .transform().language("beanshell", "file:script.bsh"); // file system resource } }
Inside your script you will have access to predefined variables like request, response or exchange which will let you generate response.
SwitchYard integrates the CDI Bean Manager with the Camel Bean Registry to allow you to reference CDI Beans in your Camel routes. Any Java class annotated with @Named in your application will be available through Camel's Bean registry.
Consider an example of where you have the following CDI bean:
@Named("StringSupport") @ApplicationScoped public class StringUtil { public String trim(String string) { return string.trim(); } }
This bean can be used inside your SwitchYard Camel Routes as follows:
public class ExampleBuilder extends RouteBuilder { public void configure() { from("switchyard://ExampleBuilder") .split(body(String.class).tokenize("\n")) .filter(body(String.class).startsWith("sally:")) .to("bean:StringSupport"); } }
See Camel's Bean Binding documentation for more details.
SwitchYard integrates with the Properties Component in Camel to make system and application properties available inside your route definitions. You can inject properties into your camel route using "{{propertyName}}" expression where "propertyName" is the name of the property. The following camel route expects the "user.name" property to be injected in the last <log> statement:
<route xmlns="http://camel.apache.org/schema/spring" id="CamelTestRoute"> <log message="ItemId [${body}]"/> <to uri="switchyard://WarehouseService?operationName=hasItem"/> <log message="Title Name [${body}]"/> <log message="Properties [{{user.name}}]"/> </route>
See the Properties section of the User Guide for more details of SwitchYard property support.
The BPM Component is a pluggable container in SwitchYard which allows a business process to be exposed as a service. One fronts their business process with a custom interface and, if desired, can easily annotate it's methods to define which should start a process, signal a process event, or abort a process.
A BPM Service is a type of Knowledge Service (the other type being a Rules Service). Thus, it is strongly suggested you familiarize yourself with the shared configuration capabilities of Knowledge Services.
To create a new BPM service in SwitchYard, you'll need the following information:
File Name : the file name that will be used to create a new, empty BPMN 2 Process definition.
Interface Type : the contract for the service being provided. BPM supports Java, WSDL, and ESB contract types.
Service Name : the name of the service your process will provide.
After clicking Finish, you will have a new service component definition for your process service and an empty BPMN process definition. The next phase in developing your BPM service is to author the BPMN 2 process definition (details outside the scope of this documentation) and then configure the BPM service component to interact with that process definition.
Interaction with a process is defined via actions on a BPM service component. Take the following service contract as an example:
package org.switchyard.userguide; public interface MyService { public void start(String data); public void signal(String data); public void stop(String data); }
Actions allow you to map an operation in the service contract to one of the following interactions with a business process:
START_PROCESS
SIGNAL_EVENT
ABORT_PROCESS_INSTANCE
Operations configured with the START_PROCESS action type will start new process instances.
When you start your process (actually, any interaction with a service whose implementation is bpm), the processInstanceId will be put into the Switchyard Context at Scope.EXCHANGE, and will be fed back to your client in a binding-specific way. For soap, it will be in the form of a soap header in the soap response envelope:
<soap:Header> <bpm:processInstanceId xmlns:bpm="urn:switchyard-component-bpm:bpm:1.0">1</bpm:processInstanceId> </soap:Header>
In future process interactions, you will need to send back that same processInstanceId, so that the correlation is done properly. For soap, that means including the same soap header that was returned in the response to be sent back with subsequent requests.
If you are using persistence, the sessionId will also be available in the Context, and will need to be fed back as well. It would look the same way in the soap header as the processInstanceId does.
Operations configured with the SIGNAL_EVENT action type will have the associated process instance signaled. As above, the processInstanceId will need to have been available in the Context so the correct process instance is correlated.
There are two other pieces of information when signaling an event:
The "id". In BPMN2 lexicon, this is known as the "signal id", but in jBPM can also be known as the "event type". This is set as the id of the annotation.
Note: In BPMN2, a signal looks like this: <signal id="foo" value="bar"/> In jBPM, it is the signal id that is respected, not the name. This might require you to tweak a tooling-generated id to whatever you want it called.
The "event object". This is the data representing the event itself. There are two ways to pass in the event object:
Via a Context object, passed similar to the processInstanceId, known as "signalEvent". If this is the case, you are limited to a String type.
Via the Message content object itself (your payload). If the signalEvent Context property is absent, the content of the Message is used as the event object.
Operations configured with the ABORT_PROCESS_INSTANCE action type will cause associated process instances to be aborted. As above, the processInstanceId will need to have been available in the Context so the correct process instance is correlated.
For you to be able to use variables inside your process, you have to declare your variable names at the process level, as well as in the Parameter Mapping (and possibly Result Mapping) of any process node that wants access to those variables. This can be done easily in the jBPM Eclipse tooling by using the Properties view when clicking on either the whitespace around the process, or on any of your process nodes. For more information, please refer to the jBPM documentation.
Mapping variables from your SwitchYard Exchange, Context or Message into jBPM process variables can be done via expressions, the default (and only currently supported) type is MVEL. Each action for a process service has a distinct set of variable mappings.
For more information on mapping variables, please see the Mappings sections of the Knowledge Services documentation.
There are two ways of consuming Services with the SwitchYard BPM component:
Invoking the BPM implementation through a gateway binding. Since the BPM component exposes a java interface fronting the business process, you can use any of the bindings provided by SwitchYard. This could be a SOAP Binding or a Camel Binding, for example. (Please refer to those sections of this guide for more information.)
Invoking other SwitchYard Services from inside a BPM process itself. To do this, you can use the SwitchYardServiceWorkItemHandler, which is provided out-of-the-box. To make authoring BPMN2 processes easier, SwitchYard provides a new widget for the Eclipse BPMN2 Modeler visual editor palette. Here is a screenshot from the "Help Desk" demo quickstart:
On the bottom right hand side under "Custom Task", you can see the SwitchYard Service widget. On the left hand side, you can see the various points of the business process where SwitchYard Services are being invoked. Once you have dropped a SwitchYard Service task in the main window, you can customize it via the Eclipse Properties Editor.
The following are properties you can use to configure the SwitchYard Service task (a.k.a. the "Dynamic" SwitchYard Service task):
Service Naming Properties
ServiceName: (required) The name of the SwitchYard service to invoke.
ServiceOperationName: (optional; default=use the single method name in the service interface, if there is just one) The name of the operation within the SwitchYard service to invoke.
Content I/O Properties
ContentInputName: (optional; default=contentInput) The process variable which the message content will be placed in.
ContentOutputName: (optional; default=contentOutput) The process variable which the message content will be gotten from.
Fault-Handling Properties (see SwitchYard Service Fault Handling below)
FaultResultName: (optional) The name of the output parameter (result variable) the fault (Exception) will be stored under.
FaultSignalId: (optional) The bpmn signal id ("event type" in jbpm lingo) that will be used to signal an event in the same process instance. The event object will be the fault (Exception). Please see Signaling a Process above.
FaultWorkItemAction: (optional; default=null) After a fault occurs, what should be done? If null, nothing is done. If complete, the current work item (SwitchYard Service task) is completed. If abort, the current work item is aborted.
You can read a more detailed explanation of the Help Desk quickstart demo, as well as how to set up Eclipse to make use of new widget, on this wiki page.
During your process execution, the SwitchYardServiceWorkItemHandler class is used to handle Switchyard Service tasks. It executes service references, per the properties specified in the panel above. Pay particular attention to the list of Fault-Handling Properties. These properties define the behavior of the SwitchYardServiceWorkItemHandler in the case were a fault is encountered when executing the service reference. There are 2 scenarios that the fault-handling covers:
"In my process flow, after the SwitchYard Service task, I would like a split gateway where I can inspect a process variable (a "flag") that can tell me that a fault occurred, so that I can diverge one way or another."
To do this, specify the FaultResultName property. The SwitchYardServiceWorkItemHandler will make the fault itself available as an output parameter of the task, so that it can be associated with a process variable, and inspected for existence in your split gateway. You must also set the FaultWorkItemAction property to complete, so that the process will continue on to your split gateway!
An example bpmn2 process can be found in our JUnit test suite here: BPMWorkTests-FaultResultProcess.bpmn
"In my process flow, I have multiple places where faults could occur, and I want to have one shared path of fault-handling."
To do this, specify the FaultSignalId property. This must match a signal id you specify in your bpmn2 process definition. You can then add an event node in your process that is triggered with this signal id; the flow from that event node on is your fault-handling path. The SwitchYardServiceWorkItemHandler will then signal the proper event with the configured id.
An example bpmn2 process can be found in our JUnit test suite here: BPMWorkTests-FaultEventrocess.bpmn
Whether you choose scenario 1 or 2 above, the question remains "What next?" If you don't specify a FaultWorkItemAction property, nothing is done. The work item is not completed, nor is it aborted. You can set the property to complete to complete the work item after a fault, or you can set the property to abort to abort the work item after a fault.
The FaultWorkItemAction property was added in SwitchYard 0.8, replacing the CompleteAfterFault property of 0.7 and earlier, at which point the default was to complete the work item.
It is possible to invoke SwitchYard Services using the standard BPMN2 Service Task <serviceTask>. It is conceptually similar, however you will use the Service Task icon from the BPMN2 Editor palette, and configure it slightly differently:
The <serviceTask> knows to invoke SwitchYard when it has an implementation="##SwitchYard" attribute.
The ServiceName is derived from the BPMN2 interfaceImplementationRef.
The ServiceOperationName is derived from the BPMN2 operationImplementationRef.
The ContentInputName is always called Parameter.
The ContentOutputName is always called Result.
A Resource represents an artifact that is required by your BPM process. It could be anything you could think of, including a properties file, a Drools Rule Language file, or whatever. But it needs to be available to the BPM component's runtime for that process. The list of resources available to your process is a configurable aspect of the BPM service component.
A WorkItemHandler is a way for you to add your own code into the business process. Simply implement the org.kie.runtime.process.WorkItemHandler interface and add a handler definition to your BPM service component.
By default, the SwitchYardServiceWorkItemHandler is always added for you by the SwitchYard Maven plugin. That handler allows you to easily call out to other SwitchYard services by name within your business process. Please see the section "Consuming a BPM Service" below for more information.
Please see the Listeners and Loggers sections found in the Knowledge Services documentation.
The Rules Component is a pluggable container in SwitchYard which allows business rules to be exposed as a service. One fronts their rules with a custom interface and, if desired, can easily annotate it's methods to define which should execute the rules. The Rules Component currently supports Drools as the rule engine. Even though it is quite simple to write rules in Drools, that project's developer tooling and business analyst tooling are very mature.
A Rules Service is a type of Knowledge Service (the other type being a BPM Service). Thus, it is strongly suggested you familiarize yourself with the shared configuration capabilities of Knowledge Services.
To create a new Rules service in SwitchYard, you'll need the following information
File Name : the file name that will be used to create a new template rules definition.
Interface Type : the contract for the service being provided. Rules services support Java, WSDL, and ESB contract types.
Service Name : the name of the service your process will provide.
Package Name : package name used for the new Rules file.
The MyService interface can be as simple as this, with no SwitchYard-specific imports:
package com.example.switchyard.docs; public interface Example { public void process(MyData data); }
The generated rule template will look like this:
package com.example.switchyard.docs import org.switchyard.Message global Message message rule "RulesExample" when // insert conditional here then // insert consequence here System.out.println("service: ExampleService, payload: " + message.getContent()); end
By default, service method invocation will create a new Drools knowledge session, execute it given the passed-in domain data, and then be cleanly disposed.
However, it is possible to configure SwitchYard so that a stateful knowledge session will be used. Specifically, it will "stick around" spanning multiple invocations. (Please visit the Drools documentation to learn more about stateless vs. stateful knowledge sessions.) To do this, you use the FIRE_ALL_RULES action type instead of EXECUTE.
There is also a new capability which allows you to insert facts into a stateful knowledge session without firing the rules (you might want to do that later). In this case, use the INSERT action type.
Mapping variables from your SwitchYard Exchange, Context or Message into Drools Globals can be done via expressions, the default (and only currently supported) type is MVEL. This can be done by configuring the rules implementation:
Your expression can use the variables exchange (org.switchyard.Exchange), context (org.switchyard.Context) or message (org.switchyard.Message). You can see in the example above is that context can be accessed in the expression as a java.util.Map. When accessing it as such, the default properties Scope is IN. This can be overridden using the contextScope attribute by changing it to OUT or EXCHANGE.
Now you can use these global variables in your Drools DRL:
package example global java.lang.String service global java.lang.String messageId global com.example.Payload payload rule "Example" when ... then ... System.out.println("service: " + service + ", messageId: " + messageId + ", payload: " + payload); end
Of course, in a more realistic scenario, the payload would be accessed in rule firing because it was inserted into the session directly by the RulesExchangeHandler, and thus evaluated (rather than being accessed as a global). See Mapping Facts below.
The default Object which is inserted into the rules engine as a fact is the SwitchYard Message's content. However, this can be overridden by specifying your own fact mappings.
IMPORTANT: If you specify your own fact mappings, the SwitchYard Message content will not be inserted as a fact. You will have to add a fact mapping with an expression of "message.content" to have it still included.
There is no point in specifying the "variable" attribute of the mappings (as done for global mappings), as the result of each expression is inserted as a nameless fact. For stateless execution, the full list of facts is passed to the StatelessKnowledgeSessions' execute(Iterable) method. For stateful execution, each fact is individually inserted into the StatefulKnowledgeSession. And for Complex Event Processing, each fact is individually inserted into the WorkingMemoryEntryPoint.
If the result of the mapping expression implements Iterable (for example, a Collection), then the result is iterated over, and each iteration is inserted as a separate fact, rather than the parent Iterable itself being inserted. This is not recursive behavior (i.e: it is only done once).
Complex Event Processing, or "CEP", is an advanced topic, and can best be explained in the Drools Fusion documentation. What will be shown here in the SwitchYard documentation is how it can be configured via XML:
<implementation.rules ...> <actions> <action id="FooStream" operation="processFooMessage" type="FIRE_UNTIL_HALT"/> <action id="BarStream" operation="processBarMessage" type="FIRE_UNTIL_HALT"/> </actions> ... <properties> <property name="drools.clockType" value="realtime"/> <property name="drools.eventProcessingMode" value="stream"/> <property name="drools.maxThreads" value="1"/> <property name="drools.multithreadEvaluation" value="false"/> </properties> </implementation.rules>
Please see the Listeners and Loggers sections found in the Knowledge Services documentation.
Please see the Channels section found in the Knowledge Services documentation.
The BPEL Component is a pluggable container in SwitchYard which allows a WS-BPEL business process to be exposed as a service through an interface defined using WSDL.
To provide a service with the BPEL component, you will have to:
Define your process using WS-BPEL (e.g. using the Eclipse BPEL editor bundled with JBossTools).
Define a WSDL interface for the BPEL service.
Define a Deployment Descriptor (e.g. using the ODE Deployment Descriptor editor bundled with JBossTools).
Add the component containing the implementation and service interface to the SwitchYard configuration.
Here is an example of the component section of the SwitchYard configuration:
<sca:component name="SayHelloService"> <bpel:implementation.bpel process="sh:SayHello" /> <sca:service name="SayHelloService"> <sca:interface.wsdl interface="SayHelloArtifacts.wsdl#wsdl.porttype(SayHello)"/> </sca:service> </sca:component>
The BPEL component contains a single 'implementation.bpel' element that identifies the fully qualified name of the BPEL process.
The component may also contain one or more service elements defining the WSDL port types through which the BPEL process can be accessed.
In the packaged Switchyard application, the BPEL process associated with this fully qualified name, must be present within the root folder of the distribution, along with the deployment descriptor (deploy.xml). An example of the deployment descriptor for the BPEL process referenced above is:
<deploy xmlns="http://www.apache.org/ode/schemas/dd/2007/03" xmlns:examples="http://www.jboss.org/bpel/examples" > <process name="examples:SayHello"> <active>true</active> <retired>false</retired> <process-events generate="all"/> <provide partnerLink="client"> <service name="examples:SayHelloService" port="SayHelloPort"/> </provide> </process> </deploy>
This section describes how a BPEL process can invoke other services.
The first step is to define the WSDL interface(s), representing the service(s) to be consumed, using an invoke element within the deployment descriptor, e.g.
<process name="ls:loanApprovalProcess"> <active>true</active> <process-events generate="all"/> <provide partnerLink="customer"> <service name="ls:loanService" port="loanService_Port"/> </provide> <invoke partnerLink="assessor" usePeer2Peer="false"> <service name="ra:riskAssessor" port="riskAssessor_Port"/> </invoke> </process>
The 'usePeer2Peer' property informs the BPEL engine not to use internal communications for sending messages between BPEL processes that may be executing within the same engine, and instead pass messages through the SwitchYard infrastructure.
For each consumed service, we then need to create a reference element within the SwitchYard configuration, to locate the WSDL file and identify the port type associated with the required WSDL service/port.
<sca:component name="loanService"> <bpel:implementation.bpel process="ls:loanApprovalProcess" /> <sca:service name="loanService"> <sca:interface.wsdl interface="loanServicePT.wsdl#wsdl.porttype(loanServicePT)"/> </sca:service> <sca:reference name="riskAssessor" > <sca:interface.wsdl interface="riskAssessmentPT.wsdl#wsdl.porttype(riskAssessmentPT)"/> </sca:reference> </sca:component>
You can inject properties into your BPEL process definition with using SwitchYardPropertyFunction.resolveProperty() XPath custom function. This bpel:copy section copies "Greeting" property value into the ReplySayHelloVar variable:
..... <bpel:copy> <bpel:from xmlns:property="java:org.switchyard.component.bpel.riftsaw.SwitchYardPropertyFunction" expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath2.0"> <![CDATA[concat(property:resolveProperty('Greeting'), $ReceiveSayHelloVar.parameters/tns:input)]]> </bpel:from> <bpel:to part="parameters" variable="ReplySayHelloVar"> <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:result]]></bpel:query> </bpel:to> </bpel:copy>
See Properties section of the User Guide for more details of SwitchYard property support.
BPEL processes can be used to implement long lived stateful business processes. However the BPEL process may need to change, over the course of its lifetime, to accomodate new requirements.
This introduces the problem of how to deal with existing active instances of the BPEL process that may not complete for weeks, months or even years. In these situations we need to have a strategy for dealing with multiple version of a BPEL process, to enable new requirements to be introduced, while still preserving the original process definitions associated with existing active process instances.
This is achieved by simply associating a version number with the BPEL process by adding it as a suffix to the BPEL file name. For example, if our BPEL process would normally be located in the file 'HelloWorld.bpel', then we simply add a hyphen followed by the version number, e.g. 'HelloWorld-32.bpel' would indicate that this is the 32nd version of this BPEL process.
When a new version of the BPEL process has been defined, it is packaged in the SwitchYard application, along side the previous versions of the BPEL process. It is important that the older version of the BPEL process remain in the SwitchYard application until there are no longer any active process instances associated with that version.
It is then important that the SwitchYard application is re-deployed, without undeploying the previous version. If the previous version of the SwitchYard application is undeployed, it will cause the BPEL engine to delete all outstanding active instances associated with the process definitions that have bene removed.
Although the BPEL process is versioned, the WSDL interfaces are not. It is important to ensure that any changes made to the WSDL interfaces are backward compatible, so that both the new and older versions of the BPEL (that still have active process instances) are not affected by the changes.
The following image shows the structure of the say_hello SwitchYard BPEL quickstart:
The important part is how the artifacts are structured within the src/main/resources folder.
The switchyard.xml configuration file is located in the META-INF folder as usual. However the BPEL deployment descriptor (deploy.xml), and the BPEL process definition are located in the root folder.
The WSDL interface definitions, and any accompanying XSD schemas, can be located in sub-folders. If they are, then the BPEL process and SwitchYard BPEL component configuration must define the correct relative path.
Knowledge Services are SwitchYard Services that leverage KIE, and thus, Drools and/or jBPM:
Given that Drools and jBPM are very tightly integrated under KIE, much of their runtime configuration can be shared by both SwitchYard's BPM component and its Rules component. Therefore, documentation on this page refers to elements that are either exactly, or structurally, identical to both the BPM and Rules components. That is to say, any configuration element you see here can be used in the same way for both BPM and Rules. Sometimes, however, the context of the element is significant, so cases like that will be identified where applicable.
For some of the configuration elements below, you might wonder why it is a shared element between both the BPM and Rules components. For example, Channels are something only applicable to Rules, right? Yes, however what if your BPM process has a node which executes business rules, and those rules reference channels? In that case, you need a way to configure channels for the rules within your process. Thus, it is documented here.
Actions are how Knowledge Services know how to map service operation invocations to their appropriate runtime counterparts. For example, when method "myOperation" is called, what should happen? Execute some business rules? Start a business process?
Using the XML below as reference, when the SwitchyYard service’s "myOperation" operation is invoked, an action of type "ACTION_TYPE" will be taken. Note that "ACTION_TYPE" is just a placeholder here. Actual ActionTypes are specific to the BPM and Rules components. Please refer to the specific documentation on those pages.
At this time, the id attribute is only applicable to the Rules component.
Please see the Mapping section below for an explanation of the globals, inputs, and outputs sections.
XML
<actions> <action id="myId" operation="myOperation" type="ACTION_TYPE"> <globals> <mapping/> </globals> <inputs> <mapping/> </inputs> <outputs> <mapping/> </outputs> </action> </actions>
Mappings are the way to move data in or out of the action for that operation. You can specify as many mappings as you like for an action, and they get grouped as globals, inputs or outputs:
Global mappings are used to provide data that is applicable to the entire action, and is often used in classic in/out param (or data-holder/provider) fashion. An example of a global mapping is a global variable specified within a Drools Rule Language (DRL) file.
Input mappings are used to provide data that represents parameters being fed into an action. An example of an input mapping for BPM could be a process variable used while starting a business process. For Rules, it could be a fact to insert into a rules engine session.
Output mappings are used to return data out of an action. An example of an output mapping would be a BPM process variable that you want to set as the outgoing (response) message’s content.
Currently, the only supported expressionType is MVEL, which is the default, so you don’t have to specify it. The expression itself can be any MVEL expression, and variables that are available to you by default are:
exchange - The current org.switchyard.Exchange.
context - The current org.switchyard.Context.
message - The current org.switchyard.Message.
Whatever the resultant value of the expression is constitutes the data that is made available to the action. Some examples:
expression="message.content" - This is the same as message.getContent().
expression="context[‘foo’]" scope="IN" - This is the same as context.getProperty("foo", Scope.IN).getValue(), in a null-safe manner.
Specifying the scope attribute only matters if you use the context variable inside your expression. If you don’t specify a scope, the default Context access (which is done like a Map, if you picked up on that), is done with Scope.EXCHANGE for global mappings, Scope.IN for input mappings, and Scope.OUT for output mappings.
Specifying the variable attribute is often optional, but this depends on the usage. For example, if you are specifying a global variable for a rule, or a process variable to put into (or get out of) a BPM process, then it is required. However, if the result of the expression is to be used as facts for rule session insertion, than specifying a variable name isn’t applicable.
XML
<mapping expression="theExpression" expressionType="MVEL" scope="IN" variable="theVariable"/>
Channels
Drools supports the notion of "Channels", which are basically "exit points" in your DRL. Here is an example:
package com.example rule "example rule" when $f : Foo ( bar > 10 ) then channels["Bar"].send( $f.getBar() ); end
XML
<channels> <channel class="com.example.BarChannel" name="Bar"/> </channels>
Channels must implement org.kie.runtime.Channel.
SwitchYard provides an out-of-the-box Channel which allows you to invoke (one-way) other SwitchYard services directly and easily from your DRL. Here is an example:
XML
<channel name="HelloWorld" reference="HelloWorld" operation="greet"/>
Attribute Reference:
class = The channel implementation class. (Default is SwitchYardServiceChannel.)
name = The channel name. (default = simple name of the implementation class)
reference = The service reference qualified name.
operation = The service reference operation name.
input = The service reference operation input name.
Listeners are used to monitor specific types of events that occur during Knowledge execution. An example of this would be to audit a BPM process, and save the audit details into a database while the process progresses. Then at a later time, these details can be reported against. There are many out-of-the-box Listeners that Drools and jBPM provide, and you can write your own. The only restriction in writing your own Listener is that it must, at the minimum, implement java.util.EventListener. However, your Listener won’t actually be registered for anything unless it also implements one of the respected KIE/Drools/jBPM Listener interfaces. For example, org.drools.event.WorkingMemoryEventListener, org.drools.event.AgendaEventListener, org.kie.event.process.ProcessEventListener, or similar.
If the Listeners provide a Constructor taking a single KieRuntimeEventManager (or KnowledgeRuntimeEventManager) as a parameter, that is used and it is assumed it will do the work of registering itself with the passed-in event manager (OOTB {{WorkingMemoryLogger}}s do this). Otherwise, a no-arg constructor is assumed, and SwitchYard will do the work of registering the Listeners for each of the respected interfaces it implements.
XML
<listeners> <listener class="org.drools.event.DebugProcessEventListener"/> <listener class="org.kie.event.rule.DebugWorkingMemoryEventListener"/> <listener class="com.example.MyListener"/> </listeners>
Loggers
Loggers are special types of Listeners, and are used to output the events that occur during Knowledge execution. Support for Loggers is done using a dedicated configuration element. Events can be logged to the CONSOLE or to a FILE (or THREADED_FILE). If they are directed to a file, that log can later be opened via the Drools Eclipse tooling.
XML
<loggers> <logger interval="2000" log="myLog" type="THREADED_FILE"/> <logger type="CONSOLE/> </loggers>
Manifest
The only configuration element more important than Actions is the Manifest, which is where you specify where the "intelligence" of the component comes from. For the BPM component, this will be, at the minimum, the location of the BPMN 2 process definition file. For the Rules component, this will most likely be the location of DRL, DSL, DSLR or XLS files. There are two ways to to configure the Manifest:
With a KIE Container. This relies upon the existence of a META-INF/kmodule.xml configuration file.
With a manually defined list of Resources.
These two options are mutually exclusive: You have to choose one or the other!
The following examples assume there is a DRL file located at classpath: com/example/MyRules.drl
META-INF/kmodule.xml
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> <kbase name="com.example"> <ksession name="my-session"/> </kbase> </kmodule>
XML
<manifest> <container sessionName="my-session"/> </manifest>
In addition to the sessionName attribute, you can also specify baseName and releaseId, if desired.
Also, scanning for updates is supported only with the container option (not the resources option). To enable this, simply set scan="true" and, optionally, scanInterval=<# of milliseconds>.
XML
<manifest> <resources> <resource location="com/example/MyProcess.bpmn" type="BPMN2"/> <resource location="com/example/MyRules.drl" type="DRL"/> </resources> </manifest>
If your resources are stored in a repository like Guvnor, they can be loaded remotely. To do so, configure a ChangeSet.xml file as a resource:
<resource location="ChangeSet.xml" type="CHANGE_SET"/>
Then, inside the ChangeSet.xml file, specify the the details of accessing the remote package:
<change-set xmlns='http://drools.org/drools-5.0/change-set' xmlns:xs='http://www.w3.org/2001/XMLSchema-instance' xs:schemaLocation='http://drools.org/drools-5.0/change-set http://anonsvn.jboss.org/repos/labs/labs/jbossrules/trunk/drools-api/src/main/resources/change-set-1.0.0.xsd'> <add> <resource source='http://localhost:8080/drools-guvnor/org.drools.guvnor.Guvnor/package/sandbox.michele/LATEST' type='PKG' basicAuthentication="enabled" username="admin" password="admin"/> </add> </change-set>
Properties are the way to provide "hints" to the underlying KIE/Drools/jBPM runtime on how certain options are configured. Rather than having to expose every single KIE/Drools/jBPM option as a configurable element or attribute within SwitchYard, they can be set as open-ended properties.
Properties are an advanced topic, so setting them should be done with care. All possible property names and values will not be listed here, but as a starting point, in your IDE open up a Type Heirarchy with a root of org.kie.conf.Option. That is your full list. Here are just a couple examples:
XML
<properties> <property name="drools.clockType" value="pseudo"/> <property name="drools.eventProcessingMode" value="stream"/> </properties>
The SOAP component in SwitchYard provides SOAP-based web service binding support for services and references in SwitchYard.
Composite-level services can be exposed as a SOAP-based web service using the <binding.soap> binding definition. The following configuration options are available for binding.soap when binding services:
wsdl : location of the WSDL used to describe the web service endpoint. A relative path can be used if the WSDL is included in the deployed application. If the WSDL is located outside the application, then a file: or http: URL can be used.
socketAddr : the IP Socket Address to be used. The value can be in the form hostName/ipAddress:portNumber or hostName/ipAddress or :portNumber.
wsdlPort : port name in the WSDL to use. If unspecified, the first port definition in the WSDL is used for the service endpoint
contextPath : additional context path for the SOAP endpoint. Default is none.
In AS7 by default the JBossWS-CXF stack is enabled now and hence the socketAddr parameter will be ignored. However this parameter can be used for standalone usage under JDK's JAXWS-RI.
Here's an example of what a SOAP service binding looks like:
<sca:composite name="orders" targetNamespace="urn:switchyard-quickstart-demo:orders:0.1.0"> <sca:service name="OrderService" promote="OrderService"> <soap:binding.soap> <soap:wsdl>wsdl/OrderService.wsdl</soap:wsdl> <soap:socketAddr>:9000</soap:socketAddr> </soap:binding.soap> </sca:service> </sca:composite>
Binding a reference with SOAP can be used to make SOAP-based web services available to SwitchYard services. The following configuration options are available for binding.soap when binding references:
wsdl : location of the WSDL used to describe the web service endpoint. A relative path can be used if the WSDL is included in the deployed application. If the WSDL is located outside the application, then a file: or http: URL can be used.
wsdlPort : port name in the WSDL to use. If unspecified, the first port definition in the WSDL is used for the service endpoint.
endpointAddress : the SOAP endpoint address to override from that specified in the WSDL. Optional property, if not specified will use the one specified in the WSDL.
<sca:composite name="orders" targetNamespace="urn:switchyard-quickstart-demo:orders:0.1.0"> <sca:reference name="WarehouseService" promote="OrderComponent/WarehouseService" multiplicity="1..1"> <soap:binding.soap> <soap:wsdl>wsdl/OrderService.wsdl</soap:wsdl> <soap:endpointAddress>http://www.change.com/toanewendpointurl</soap:endpointAddress> </soap:binding.soap> </sca:reference> </sca:composite>
To enable WS-Security within your application, a few steps are required:
Define a Policy within your WSDL, and reference with with a PolicyReference inside your binding.
Configure your <soap.binding> with a <securityAction so JBossWS-CXF knows which tokens to respect within incoming SOAP requests.
Include a WEB-INF/jboss-web.xml in your application with a <security-domain> specified, so JBossWS-CXF (who, in the case of WS-Security, is doing the JAAS login "at the front door") knows which modules to use for authentication and roles mapping.
SwitchYard provides a policy-security-wss-username Quickstart as an example. Here are the pertinent sections:
META-INF/WorkService.wsdl
<binding name="WorkServiceBinding" type="tns:WorkService"> <wsp:PolicyReference URI="#WorkServicePolicy"/> ... </binding> <wsp:Policy wsu:Id="WorkServicePolicy"> <wsp:ExactlyOne> <wsp:All> <sp:SupportingTokens xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702"> <wsp:Policy> <sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient"> <wsp:Policy> <sp:WssUsernameToken10/> </wsp:Policy> </sp:UsernameToken> </wsp:Policy> </sp:SupportingTokens> </wsp:All> </wsp:ExactlyOne> </wsp:Policy>
META-INF/switchyard.xml
<binding.soap xmlns="urn:switchyard-component-soap:config:1.0"> <wsdl>META-INF/WorkService.wsdl</wsdl> <contextPath>policy-security-wss-username</contextPath> <securityAction>UsernameToken</securityAction> </binding.soap>
WEB-INF/jboss-web.xml
<jboss-web> <security-domain>java:/jaas/other</security-domain> </jboss-web>
With the above pieces in place, JBossWS-CXF will intercept incoming SOAP requests, extract the UsernameToken, attempt to authenticate it against the LoginModule(s) configured in the application server's "other" security domain, and provide any authorized roles. If successful, the request will be handed over to SwitchYard, who can do further processing, including enforcing our own policies. In the case of WS-Security, SwitchYard will not attempt a second clientAuthentication, but instead will respect the outcome from JBossWS-CXF. Note that if the original clientAuthentication fails, it is a "fail-fast" scenario, and the request will not be channeled into SwitchYard.
In the current release, support for WS-Security Signature and Encryption requires additional, manual steps. The next release will streamline the process significantly.
The Policy in your WSDL needs to reflect the added requirements. An example of this can be found in the JBossWS documentation here: Signature and Encryption.
Manual addition of a CXF InInterceptor which sets certain CXF security properties is currently required.
Accomplishing that last point can be done like this:
META-INF/switchyard.xml
<binding.soap xmlns="urn:switchyard-component-soap:config:1.0"> <wsdl>META-INF/WorkService.wsdl</wsdl> <contextPath>policy-security-wss-username</contextPath> <inInterceptors> <interceptor class="com.example.MyInterceptor"/> </inInterceptors> </binding.soap>
com/example/MyInterceptor.java
public class MyInterceptor extends WSS4JInterceptor { private static final PROPS; static { Map<String,String> props = new HashMap<String,String>(); props.put("action", "Signature Encryption"); props.put("signaturePropFile", "META-INF/bob.properties"); props.put("decryptionPropFile", "META-INF/bob.properties"); props.put("passwordCallbackClass", "com.example.MyCallbackHandler"); PROPS = props; } public MyInterceptor() { super(PROPS); } }
META-INF/bob.properties
org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin org.apache.ws.security.crypto.merlin.keystore.type=jks org.apache.ws.security.crypto.merlin.keystore.password=password org.apache.ws.security.crypto.merlin.keystore.alias=bob org.apache.ws.security.crypto.merlin.file=META-INF/bob.jks
The HTTP component in SwitchYard provides HTTP-based binding support for services and references in SwitchYard.
Composite-level services can be exposed as a HTTP-based service using the <binding.http> binding definition. The following configuration options are available for binding.rest when binding services:
operationSelector : specification of the operation to use for the message exchange. See Operation Selector for more details.
contextPath : A context path for the HTTP endpoint.
Here's an example of what a HTTP service binding looks like:
<sca:service name="QuoteService" promote="StockService/QuoteService"> <http:binding.http> <selector:operationSelector operationName="getPrice"/> <http:contextPath>http-binding/quote</http:contextPath> </http:binding.http> </sca:service>
Binding a reference with HTTP can be used to make HTTP-based services available to SwitchYard services. The following configuration options are available for binding.http when binding references:
address : A URL that points to the HTTP endpoint. It is optional and if not specified will default to http://127.0.0.1:8080/.
method : The HTTP method used for invoking the endpoint. Default is GET.
contentType : The HTTP Content-Type header that needs to be set on the request.
Here's an example of what a REST reference binding looks like:
<sca:reference name="Symbol" promote="StockService/SymbolService" multiplicity="1..1"> <http:binding.http> <http:address>http://localhost:8080/http-binding/symbol</http:address> <http:method>POST</http:method> <http:contentType>text/plain</http:contentType> </http:binding.http> </sca:reference>
The RESTEasy component in SwitchYard provides REST-based binding support for services and references in SwitchYard.
Composite-level services can be exposed as a REST-based service using the <binding.rest> binding definition. The following configuration options are available for binding.rest when binding services:
interfaces : A comma seperated list of interfaces or abstract/empty classes with JAX-RS annotations.
contextPath : Additional context path for the REST endpoint. Default is none.
Here's an example of what a REST service binding looks like:
<sca:service name="OrderService" promote="OrderService/OrderService"> <rest:binding.rest> <rest:interfaces>org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource</rest:interfaces> <rest:contextPath>rest-binding</rest:contextPath> </rest:binding.rest> </sca:service>
Binding a reference with REST can be used to make REST-based services available to SwitchYard services. The following configuration options are available for binding.rest when binding references:
interfaces : A comma seperated list of interfaces or abstract/empty classes with JAX-RS annotations.
address : A URL that points to the root path of resources. This is only applicable for Reference bindings. It is optional and if not specified will default to http://127.0.0.1:8080/.
contextPath : Additional context path for the REST endpoint. Default is none.
Here's an example of what a REST reference binding looks like:
<sca:reference name="Warehouse" promote="OrderService/Warehouse" multiplicity="1..1"> <rest:binding.rest> <rest:interfaces>org.switchyard.quickstarts.rest.binding.WarehouseResource</rest:interfaces> <rest:address>http://localhost:8080</rest:address> <rest:contextPath>rest-binding</rest:contextPath> </rest:binding.rest> </sca:reference>
In this example above the resource URLs will start from http://localhost:8080/rest-binding.
The JCA gateway allows you to send and receive messages to/from EIS via JCA ResourceAdapter.
Composite-level services can be bound to a EIS with JCA message inflow using the <binding.jca> binding definition. The following configuration options are required for binding.jca:
operationSelector : specification of the operation to use for the message exchange. See Operation Selector for more details.
inboundConnection
resourceAdapter
@name : Name of the ResourceAdapter archive. Please make sure the resource adapter has been deployed on JBoss application server before you deploy the SwitchYard application which has JCA binding.
activationSpec
property : Properties to be injected into ActivationSpec instance. Required properties are specific to the ResourceAdapter implementation.
inboundInteraction
listener : FQN of the listener interface. When you use JMSEndpoint, javax.jms.MessageListener should be specified. When you use CCIEndpoint, javax.resource.cci.MessageListener should be specified. Otherwise, you may need to specify EIS specific listener interface according to its ResourceAdapter. Note that the endpoint class should implement this listener interface.
endpoint
@type : FQN of the Endpoint implementation class. There are 2 built-in Endpoint, org.switchyard.component.jca.endpoint.JMSEndpoint and org.switchyard.component.jca.endpoint.CCIEndpoint. Note that these 2 have corresponding listener. If neither JMSEndpoint nor CCIEndpoint is applicable for the EIS you're supposed to bind to, then you need to implement its own Endpoint class according to the ResourceAdapter implementation. The Endpoint class should be a subclass of org.switchyard.component.jca.endpoint.AbstractInflowEndpoint.
property : Properties to be injected into Endpoint class. JMSEndpoint has no required property. CCIEndpoint needs connectionFactoryJNDIName property.
transacted : The boolean value to indicate whether transaction is needed by endpoint or not. True by default.
batchCommit : Multiple incoming messages are processed in one transaction if you define this element. The transaction is committed when the number of processed messages reach to batchSize, or batchTimeout milliseconds pass since the transaction is started. Transaction reaper thread is watching inflight transaction, and once batch timeout occurs the transaction reaper thread commits it.
@batchSize : The number of messages to be processed in one transaction
@batchTimeout : The batch timeout in milliseconds
Here's an example of what a JCA service binding looks like. This example binds a service to the HornetQ JMS:
<sca:composite name="JCAInflowExample" targetNamespace="urn:userguide:jca-example-service:0.1.0"> <sca:service name="JCAService" promote="SomeService"> <jca:binding.jca> <selector:operationSelector operationName="onMessage"/> <jca:inboundConnection> <jca:resourceAdapter name="hornetq-ra.rar"/> <jca:activationSpec> <jca:property name="destinationType" value="javax.jms.Queue"/> <jca:property name="destination" value="ServiceQueue"/> </jca:activationSpec> </jca:inboundConnection> <jca:inboundInteraction> <jca:listener>javax.jms.MessageListener</jca:listener> <jca:endpoint type="org.switchyard.component.jca.endpoint.JMSEndpoint"/> <jca:transacted>true</jca:transacted> <jca:batchCommit batchSize="10" batchTimeout="5000"/> </jca:inboundInteraction> </jca:binding.jca> </service> <!-- sca:component definition omitted --> </sca:composite>
Composite-level references can be bound to a EIS with JCA outbound using the <binding.jca> binding definition. The following configuration options are required for binding.jca:
outboundConnection
resourceAdapter
@name : Name of the ResourceAdapter archive. Please make sure the resource adapter has been deployed on JBoss application server before you deploy the SwitchYard application which has JCA binding.
connection
@jndiName : JNDI name which the ConnectionFactory is bound into.
outboundInteraction
connectionSpec : Configuration for javax.resource.cci.ConnectionSpec. Note that JMSProcessor doesn't use this option.
@type : FQN of the ConnectionSpec implementation class.
property : Properties to be injected into ConnectionSpec instance.
interactionSpec : Configuration for _javax.resource.cci.InteractionSpec. _Note that JMSProcessor doesn't use this option.
@type : FQN of the InteractionSpec implementation class.
property : Properties to be injected into InteractionSpec instance.
processor
@type : FQN of the class which processes outbound delivery. There are 2 build-in processor, org.switchyard.component.jca.processor.JMSProcessor and org.switchyard.component.jca.processor.CCIProcessor. If neither JMSProcessor nor CCIProcessor is applicable for the EIS you're supposed to bind to, then you need to implement its own processor class according to the ResourceAdapter implementation. Note that this class should be a subclass of org.switchyard.component.jca.processor.AbstractOutboundProcessor.
property : Properties to be injected into processor instance. JMSProcessor needs destination property to specify target destination. CCIProcessor needs recordClassName property to specify record type to be used to interact with EIS. If you use CCIProcessor with the record type other than MappedRecord and IndexedRecord, you need to implement corresponding RecordHandler. Please refer to org.switchyard.component.jca.processor.cci.IndexedRecordHandler and org.switchyard.component.jca.processor.cci.MappedRecordHandler.
Here's an example of what a JCA reference binding looks like. This example binds a reference to the HornetQ JMS:
<sca:composite name="JCAReferenceExample" targetNamespace="urn:userguide:jca-example-reference:0.1.0"> <sca:reference name="JCAReference" promote="SomeComponent/SomeReference" multiplicity="1..1"> <jca:binding.jca> <jca:outboundConnection> <jca:resourceAdapter name="hornetq-ra.rar"/> <jca:connection jndiName="java:/JmsXA"/> </jca:outboundConnection> <jca:outboundInteraction> <jca:processor type="org.switchyard.component.jca.processor.JMSProcessor"> <jca:property name="destination" value="ReferenceQueue"/> </jca:processor> </jca:outboundInteraction> </jca:binding.jca> </sca:reference> </sca:composite>
The JMS binding in SwitchYard provides support for asynchronous communication with messaging providers. It supports both sides - service and reference. The JMS binding is built on top of camel-jms and supports most of options for this endpoint. Please reffer camel documentation for detailed description of them.
https://issues.jboss.org/browse/SWITCHYARD-1285 - Declarative transaction management by the Transaction Policy doesn't work with camel-jms properly. We are investigating how can we solve it, but you may want to use JCA gateway instead for now.
Following options can be apile to <binding.jms> definition:
queue or topic : destination name to consume from/produce to
connectionFactory : an instance of connection factory to use
username
password
clientId
durableSubscriptionName
concurrentConsumers
maxConcurrentConsumers
disableReplyTo
preserveMessageQos
deliveryPersistent
priority
explicitQosEnabled
replyTo
replyToType
requestTimeout
selector
timeToLive
transacted
transactionManager
Here's an example of what a jms service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.jms> <camel:queue>INCOMING_GREETS</camel:queue> <camel:connectionFactory>#connectionFactory</camel:connectionFactory> <camel:username>esb</camel:username> <camel:password>rox</camel:password> <camel:selector>RECEIVER='ESB' AND SENDER='ERP'<camel:selector> </camel:binding.jms> </sca:service> </sca:composite>
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:reference name="GreetingService" promote="camel-binding/GreetingService" multiplicity="1..1"> <camel:binding.jms> <camel:topic>GREETINGS_NOTIFICATION</camel:topic> <camel:connectionFactory>#connectionFactory</camel:connectionFactory> <camel:priority>8</camel:priority> <camel:binding.jms> </sca:reference> </sca:composite>
The file binding in SwitchYard provides filesystem level support for services and references in SwitchYard.
The file binding is built on top of camel-file and supports most of options for this endpoint. Please refer camel documentation for detailed description of them.
Following options can be apiled to <binding.file> definition:
directory : directory to consume/produce files to
autoCreate : automatically create directory if doesn't exist
bufferSize : write buffer size
fileName : file name filter for consumer or file name pattern for producer
flatten : skip path and just use file name
charset : charset used for reading/wrinting file
Supported options are:
delete
recursive
noop
preMove
move
moveFailed
include
exclude
idempotent
idempotentRepository
inProgressRepository
filter
sorter
sortBy
readLock
readLockTimeout
readLockCheckInterval
exclusiveReadLockStrategy
processStrategy
startingDirectoryMustExist
directoryMustExist
doneFileName
Here's an example of what a file service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.file> <camel:directory>target/input</camel:directory> <camel:fileName>test.txt</camel:fileName> <camel:consume> <camel:initialDelay>50</camel:initialDelay> <camel:delete>true</camel:delete> </camel:consume> </camel:binding.file> </sca:service> </sca:composite>
Binding a reference with file can be used to store outcome of service on disk. The following configuration options are available for binding.file when binding references:
fileExist
tempPrefix
tempFileName
keepLastModified
eagerDeleteTargetFile
doneFileName
For detailed description of these parameters please refer camel-file documentation
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:reference name="GreetingService" promote="camel-binding/GreetingService" multiplicity="1..1"> <camel:binding.file> <camel:directory>target/output</camel:directory> <camel:autoCreate>false</camel:autoCreate> <camel:produce> <camel:fileExist>Override</camel:fileExist> </camel:produce> <camel:binding.file> </sca:reference> </sca:composite>
SwitchYard provides support for remote file systems on both sides service and reference.
The ftp binding is built on top of camel-ftp and supports most of options for this endpoint. Please refer camel documentation for detailed description of them.
Following options can be apiled to <binding.ftp> <binding.ftps> and <binding.sftp> definition:
host
port
username
password
binary
connectTimeout
disconnect
maximumReconnectAttempts
reconnectDelay
separator
stepwise
throwExceptionOnConnectFailed
passiveMode
timeout
soTimeout
siteCommand
securityProtocol
isImplicit
execPbsz
execProt
disableSecureDataChannelDefaults
knownHostsFile
privateKeyFile
privateKeyFilePassphrase
Supported options are same as for File.
Here's an example of what a file service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.ftp> <camel:directory>target/input</camel:directory> <camel:host>localhost</camel:host> <camel:port>22</camel:port> <camel:username>camel</camel:username> <camel:password>secret</camel:password> <camel:consume> <camel:initialDelay>50</camel:initialDelay> <camel:delete>true</camel:delete> </camel:consume> </camel:binding.file> </sca:service> </sca:composite>
Binding a reference with file can be used to store outcome of service on remote server. All File referene properties are supported.
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:reference name="GreetingService" promote="camel-binding/GreetingService" multiplicity="1..1"> <camel:binding.ftp> <camel:directory>target/output</camel:directory> <camel:autoCreate>false</camel:autoCreate> <camel:host>localhost</camel:host> <camel:port>22</camel:port> <camel:username>camel</camel:username> <camel:password>secret</camel:password> <camel:produce> <camel:fileExist>Override</camel:fileExist> </camel:produce> <camel:binding.ftp> </sca:reference> </sca:composite>
SwitchYard provides support for network level integration with TCP and UPD protocols.
The TCP and UDP binding is built on top of camel-netty and supports most of options for this endpoint. Please refer camel documentation for detailed description of them.
Following options can be apiled to <binding.tcp> and <binding.udp definition:
host
port
receiveBufferSize
sendBufferSize
reuseAddress
encoders
decoders
allowDefaultCodec
workerCount
sync
disconnect
textline
tcpNoDelay
keepAlive
broadcast
This endpoint supports SSL. Following parameters may be used to configure it:
ssl - turn on SSL
sslHandler - custom SSL Handler to use
passphrase - bean reference to String instance used to open KeyStore
securityProvider - name of Java security provider
keyStoreFormat
keyStoreFile - reference to File instance which is used loaded into java KeyStore
trustStoreFile - reference to File instance
sslContextParametersRef - if this parameter is specified it must be an bean reference to an instance of org.apache.camel.util.jsse.SSLContextParameters where you may specify all necessary parameters at once.
Here's an example of what a file service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.tcp> <camel:host>localhost</camel:host> <camel:port>3939</camel:port> <camel:allowDefaultCodec>false</camel:allowDefaultCodec> <camel:sync>false</camel:sync> </camel:binding.tcp> <camel:binding.udp> <camel:host>localhost</camel:host> <camel:port>3940</camel:port> <camel:allowDefaultCodec>false</camel:allowDefaultCodec> <camel:sync>false</camel:sync> </camel:binding.udp> </sca:service> </sca:composite>
The jpa binding in SwitchYard provides support for consuming and storing JPA entities. It supports both sides - service binding for entity consumption and reference for entity storing.
The JPA binding is built on top of camel-jpa and supports most of options for this endpoint. Please reffer camel documentation for detailed description of them.
Following options can be apiled to <binding.jpa> definition:
entityClassName
persistenceUnit
transactionManager
Supported options are:
consumeDelete
consumeLockEntity
maximumResults
consumer.query
consumer.namedQuery
consumer.nativeQuery
consumer.resultClass
consumer.transacted
The consumeLockEntity option causes problems with transaction management.
Here's an example of what a mail service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.jpa> <camel:entityClassName>org.switchyard.quickstarts.camel.jpa.binding.domain.Greet</camel:entityClassName> <camel:persistenceUnit>JpaEvents</camel:persistenceUnit> <camel:transactionManager>#jtaTransactionManager</camel:transactionManager> <camel:consume> <camel:consumeLockEntity>false</camel:consumeLockEntity> <camel:consumer.transacted>true</camel:consumer.transacted> </camel:consume> </camel:binding.jpa> </sca:service> </sca:composite>
Binding a reference with jpa can be used to store entity. The following configuration options are available for binding.jpa when binding references:
flushOnSend
usePersist
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:reference name="GreetingService" promote="camel-binding/GreetingService" multiplicity="1..1"> <camel:binding.jpa> <camel:entityClassName>org.switchyard.quickstarts.camel.jpa.binding.domain.Greet</camel:entityClassName> <camel:persistenceUnit>JpaEvents</camel:persistenceUnit> <camel:produce> <camel:flushOnSend>false</camel:flushOnSend> </camel:produce> </camel:binding.jpa> </sca:reference> </sca:composite>
The sql binding in SwitchYard provides database read/write support for references in SwitchYard.
The file binding is built on top of camel-sql.
Following options can be apiled to <binding.sql> definition:
query : SQL query to execute
dataSourceRef : data source name
batch : turn on JDBC batching
placeholder : a placeholder sign used to replace parameters in query
For detailed description of these parameters please visit camel-sql site.
Two additional attributes may be specified for binding.sql element when used with service reference:
period - number of milliseconds between query executions. This attribute is mandatory.
initialDelay - an delay before query is run first time
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.sql period="10s"> <camel:query>SELECT * FROM greetings</camel:query> <camel:dataSourceRef>java:jboss/datasources/GreetDS</camel:dataSourceRef> </camel:binding.sql> </sca:service> </sca:composite>
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:reference name="GreetingDatabaseStore" promote="camel-binding/GreetingDatabaseStore" multiplicity="1..1"> <camel:binding.sql> <camel:query>INSERT INTO greetings (name) VALUES (#)</camel:query> <camel:dataSourceRef>java:jboss/datasources/GreetDS</camel:dataSourceRef> <camel:binding.sql> </sca:reference> </sca:composite>
The mail binding in SwitchYard provides support for consuming and sending mail messages. It supports both sides - service binding for mail consumption and reference for message sending.
The Mail binding is built on top of camel-mail and supports most of options for this endpoint. Please reffer camel documentation for detailed description of them.
Following options can be apiled to <binding.mail> definition:
host
port
username
password
connectionTimeout
Additional attribute secure may be used to identify usage of secured connection (pop3s/imaps/smtps) instead.
Supported options are:
folderName
fetchSize
unseen
delete
copyTo
disconnect
Additional attribute accountType may be specified to choose mail protocol. Possible values are pop3 or imap. Default is imap.
Here's an example of what a mail service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.mail> <camel:host>localhost</camel:host> <camel:username>camel</camel:username> <camel:consume accountType="pop3"> <camel:copyTo>after-processing</camel:copyTo> </camel:consume> </camel:binding.mail> </sca:service> </sca:composite>
Binding a reference with mail can be used to send outgoing message. The following configuration options are available for binding.mail when binding references:
subject
from
to
CC
BCC
replyTo
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:reference name="GreetingService" promote="camel-binding/GreetingService" multiplicity="1..1"> <camel:binding.mail> <camel:host>localhost</camel:host> <camel:username>camel</camel:username> <camel:produce> <camel:subject>Forwarded message</camel:subject> <camel:from>camel@localhost</camel:from> <camel:to>rider@camel</camel:to> </camel:produce> </camel:binding.mail> </sca:reference> </sca:composite>
The quartz binding in SwitchYard provides support for triggering services with given cron expression.
The quartz binding is built on top of camel-quartz.
Following options can be apile to <binding.quartz> definition:
name : name of job
cron : execution expression
Here's an example of what a quartz service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.quartz> <camel:name>GreetingJob</camel:name> <camel:cron>0 0/5 * * * ?</camel:cron> </camel:binding.quartz> </sca:service> </sca:composite>
The timer binding in SwitchYard provides support for triggering services with fixed timer. It's lightweight alternative for Quartz.
The file binding is built on top of camel-timer. Please refer camel documentation for detailed description of options.
Following options can be apiled to <binding.timer> definition:
name : name of timer
time
pattern
period
delay
fixedRate
daemon
Here's an example of what a timer service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.timer> <camel:name>GreetingTimer</camel:name> <camel:time>2012-01-01T12:00:00</camel:time> <camel:pattern>yyyy-MM-dd'T'HH:mm:ss</camel:pattern> <camel:delay>1000</camel:delay> <camel:fixedRate>true</camel:fixedRate> </camel:binding.timer> </sca:service> </sca:composite>
The SEDA binding in SwitchYard provides asynchronous service binding between camel route and SwitchYard service.
SEDA queue is not persistent.
This binding is built on top of camel-seda. Please refer camel documentation for detailed description of options.
Following options can be apiled to <binding.seda> definition:
name : queue name
size : the maximum capacity of the SEDA queue (the number of messages it can hold)
concurrentConsumers
waitForTaskToComplete
timeout
multipleConsumers
limitConcurrentConsumers
Here's an example of what a SEDA service binding looks like:
<sca:composite name="camel-binding" targetNamespace="urn:switchyard-quickstart:camel-binding:0.1.0"> <sca:service name="GreetingService" promote="GreetingService"> <camel:binding.seda> <camel:name>GreetingQueue</camel:name> <camel:size>6</camel:size> <camel:concurrentConsumers>2</camel:concurrentConsumers> </camel:binding.seda> </sca:service> </sca:composite>
Camel binding support in SwitchYard allows Camel components to be used as gateway bindings for services and references within an application.
Every camel component binding supported by SwitchYard has it's own configuration namespace. However, there is asmall exception. Bindings for direct, seda, timer and mock share same namespace urn:switchyard-component-camel-core:config:1.0.
Composite-level services can be bound to a Camel component using the <binding.uri> binding definition. The following configuration options are available for binding.uri:
configURI : contains the Camel endpoint URI used to configure a Camel component instance
operationSelector : specification of the operation to use for the message exchange. See Operation Selector for more details. This setting is not used for cxfrs configurations.
binding.uri is not linked with any specific component. It allows usage of 3rd party camel components which are not part of distribution.
Before SwitchYard 0.7 binding.camel element was used instead of binding.uri
Here's an example of what a service binding looks like using a Camel component.
<sca:composite name="SimpleCamelService" targetNamespace="urn:userguide:simple-camel-service:0.1.0"> <sca:service name="SimpleCamelService" promote="SimpleComponent/SimpleCamelService"> <camel:binding.uri configURI="file://target/input?fileName=test.txt&initialDelay=50&delete=true"> <selector:operationSelector operationName="print"/> </camel:binding.uri> </sca:service> <!-- sca:component definition omitted --> </sca:composite>
Binding a reference with Camel is very similar to binding a service. The only significant difference is that specification of the operationSelector is not required on reference bindings. Logically reference elements points to outgoing communication eg. service called by Switchyard.
<sca:composite name="orders" targetNamespace="urn:switchyard-quickstart-demo:orders:0.1.0"> <sca:reference name="WarehouseService" promote="OrderComponent/WarehouseService" multiplicity="1..1"> <camel:binding.uri configURI="file://target/output"/> </sca:reference> </sca:composite>
A MessageComposer can compose or decompose a native binding message to/from SwitchYard's canonical message. A MessageComposer does this in three steps:
Construct a new target message instance.
Copy the content ("body") of the message.
Delegate the header/property mapping to a ContextMapper.
We currently provide a SOAPMessageComposer, a CamelMessageComposer, and a HornetQMessageComposer. These default implementations are used by their associated bindings, but can be overridden by the user.
To implement a custom MessageComposer, you need to implement the org.switchyard.component.common.composer.MessageComposer interface:
public interface MessageComposer<T> { ContextMapper<T> getContextMapper(); MessageComposer<T> setContextMapper(ContextMapper<T> contextMapper); Message compose(T source, Exchange exchange, boolean create) throws Exception; public T decompose(Exchange exchange, T target) throws Exception; }
The getContextMapper() and setContextMapper() methods are just bean properties. If you extend BaseMessageComposer, both of these are implemented for you.
Your compose() method needs to take the data from the passed in source native message and compose a SwitchYard Message based on the specified Exchange. The create parameter is whether or not we ask the Exchange to create a new Message, or just get the existing one.
Your decompose() method needs to take the data from the SwitchYard Message in the specified Exchange and decompose it into the target native message.
Then, specify your implementation in your switchyard.xml:
<binding.xyz ...> <messageComposer class="com.example.MyMessageComposer"/> </binding.xyz>
A ContextMapper moves native binding message headers and/or properties to/from SwitchYard's canonical context. We provide many ContextMapper implementations OOTB (see section below). These default implementations are used by their associated bindings, but can be overridden by the user.
To implement a custom ContextMapper, you need to implement the org.switchyard.component.common.composer.ContextMapper interface:
public interface ContextMapper<T> { void mapFrom(T source, Context context) throws Exception; void mapTo(Context context, T target) throws Exception; }
Your mapFrom() method needs to map a source native message's properties to the SwitchYard Message's Context.
Your mapTo() method needs to map a SwitchYard Message's Context properties into the target native message.
If you extend BaseContextMapper, these methods are stubbed-out with no-op implementations so you only have to implement what you want to.
Then, specify your implementation in your switchyard.xml:
<binding.xyz ...> <contextMapper class="com.example.MyContextMapper"/> </binding.xyz>
Alternatively, you can implement the org.switchyard.component.common.composer.RegexContextMapper. The purpose of this interface is to add regular expression support, where you can filter exactly which Context properties get mapped:
public interface RegexContextMapper<T> extends ContextMapper<T> { ContextMapper<T> setIncludes(String includes); ContextMapper<T> setExcludes(String excludes); ContextMapper<T> setIncludeNamespaces(String includeNamespaces); ContextMapper<T> setExcludeNamespaces(String excludeNamespaces); boolean matches(String name); boolean matches(QName qname); }
The setIncludes(), setExcludes(), setIncludeNamespaces() and setExcludeNamespaces() methods are just bean properties. The matches() methods use those bean properties to determine if the specified name or qualified name passes the collective regular expressions.
If you extend BaseRegexContextMapper, all of these are implemented for you. Then, in your implementation's mapFrom / mapTo methods, you only need to first check if the property matches before you map it.
If your implementation extends RegexContextMapper, the following additional (regular expression valued) attributes of the <contextMapper/> element become meaningful/respected:
includes = Which context property names to include.
excludes = Which context property names to exclude.
includeNamespaces = Which context property namespaces to include (if the property name is a qualified name).
excludeNamespaces = Which context property namespaces to exclude (if the property name is a qualified name).
Note: All of the out-of-the-box implementations below extend BaseRegexContextMapper, thus all can be configured with the regular expression attributes described above.
The SOAPContextMapper, when processing an incoming SOAPMessage, takes the mime (in most cases, HTTP) headers from a soap envelope and maps them into the SwitchYard Context as Scope.IN properties with the SOAPComposition.SOAP_MESSAGE_MIME_HEADER label, and takes the soap header elements from the soap envelope and maps them into the SwitchYard Context as Scope.EXCHANGE properties with the SOAPComposition.SOAP_MESSAGE_HEADER label. When processing an outgoing SOAPMessage, it takes the SwitchYard Scope.OUT Context properties and maps them into mime (in most cases, HTTP) headers, and takes the SwitchYard Scope.EXCHANGE Context properties and maps them into the soap envelope as soap header elements.
The SOAPContextMapper has an additional attribute that the other OOTB ContextMappers do not have: soapHeadersType:
<binding.soap> <contextMapper includes=".*" soapHeadersType="VALUE"/> </binding.soap>
The value of soapHeadersType can be CONFIG, DOM, VALUE or XML (and correspond to the enum SOAPHeadersType.CONFIG, DOM, VALUE or XML). With CONFIG, each soap header element is mapped into an org.switchyard.config.Configuration object, with DOM, each soap header element is left as is (a DOM element), with VALUE, just the String value of each soap header element is stored, and with XML, each soap header element is transformed into an XML String.
The CamelContextMapper, when processing an incoming CamelMessage, takes the CamelMessage headers and maps them into the SwitchYard Context as Scope.IN properties with the CamelComposition.CAMEL_MESSAGE_HEADER label, and takes the Camel Exchange properties and maps them into the SwitchYardContext as Scope.EXCHANGE properties with the CamelComposition.CAMEL_EXCHANGE_PROPERTY label. When processing an outgoing CamelMessage, it takes the SwitchYard Scope.OUT Context properties and maps them into the CamelMessage as headers, and takes the SwitchYard Scope.EXCHANGE Context properties and maps them into the Camel Exchange as properties.
The HornetQContextMapper, when processing an incoming ClientMessage, takes the ClientMessage properties and maps them into the SwitchYardContext as Scope.EXCHANGE properties with the HornetQCompsition.HORNETQ_MESSAGE_PROPERTY label. When procesing an outgoing ClientMessage, it takes the SwitchYard Scope.EXCHANGE Context properties and maps them into the ClientMessage as properties. There is no concept of "headers" in a HornetQ ClientMessage.
The HTTPContextMapper, when processing an incoming HTTP request, takes the incoming request headers and maps them into the SwitchYard Context as Scope.IN with the HttpComposition.HTTTP_HEADER label. When processing an outgoing HTTP response, it takes the SwitchYard Scope.OUT Context properties and maps them into the response headers.
The RESTEasyContextMapper, when processing an incoming HTTP request, takes the incoming request headers and maps them into the SwitchYard Context as Scope.IN with the RESTEasyComposition.HTTP_HEADER label. When processing an outgoing HTTP response, it takes the SwitchYard Scope.OUT Context properties and maps them into the response headers.
The JCA Component actually has 3 different ContextMappers:
The CCIIndexedRecordContextMapper, when processing an incoming IndexedRecord, takes the record name and record short description and maps them into the SwitchYardContext as Scope.EXCHANGE properties with the JCAComposition.JCA_MESSAGE_PROPERTY label. When processing an outgoing IndexedRecord, it looks for those properties specifically in the SwitchYard.EXCHANGE Context properties by key and sets them on the IndexedRecord.
The CCIMappedRecordContextMapper, when processing an incoming MappedRecord, takes the record name and record short description and maps them into the SwitchYardContext as Scope.EXCHANGE properties with the JCAComposition.JCA_MESSAGE_PROPERTY label. When processing an outgoing MappedRecord, it looks for those properties specifically in the SwitchYard.EXCHANGE Context properties by key and sets them on the MappedRecord.
The JMSContextMapper, when processing an incoming (JMS) Message, takes the Message properties and maps them into the SwitchYardContext as Scope.EXCHANGE properties with the JCAComposition.JCA_MESSAGE_PROPERTY label. When processing an outgoing (JMS) Message, it takes the SwitchYard.EXCHANGE Context properties and maps them into the Message as Object properties.
The reasoning of scoping headers as IN and OUT scopes was modeled after the notion of http headers, where you will see some headers specifically useful for http requests, and other headers specifically useful for http responses. In both cases, they are most likely tied to the binding's notion of an incoming message or an outgoing message.
The reasoning of scoping properties as EXCHANGE scope came from the idea that this is most likely application or domain data, and possibly useful in the entire processing of the Exchange. An example of this would be a processInstanceId when using the BPM Component.
OperationSelector provides a capability to determine which service operation should be invoked for the message exchange. The following options are available. If the target service only has a single operation, this setting is optional.
specify a operation name in the configuration.
<hornetq:binding.hornetq> <swyd:operationSelector operationName="greet" xmlns:swyd="urn:switchyard-config:switchyard:1.0"/> (... snip ...) </hornetq:binding.hornetq>
specify a XPath location which contains a operation name to be invoked in the message contents.
If the configuration looks like this:
<jca:binding.jca> <swyd:operationSelector.xpath expression="//person/language" xmlns:swyd="urn:switchyard-config:switchyard:1.0"/> (... snip ...) </jca:binding.jca>
And the message content is like this:
<person> <name>Fernando</name> <language>spanish</language> </person>
Then operation spanish() would be invoked.
specify a Regular Expression to find a operation name to be invoked in the message contents.
If the configuration looks like this:
<http:binding.http> <swyd:operationSelector.regex expression="[a-zA-Z]*Operation" xmlns:swyd="urn:switchyard-config:switchyard:1.0"/> (... snip ...) </http:binding.http>
And the message content is like this:
xxx yyy zzz regexOperation aaa bbb ccc
Then operation regexOperation() would be invoked.
specify a Java class which is able to determine the operation to be invoked.
configuration should look like this:
<jca:binding.jca> <swyd:operationSelector.java class="org.switchyard.example.MyOperationSelectorImpl" xmlns:swyd="urn:switchyard-config:switchyard:1.0"/> (... snip ...) </jca:binding.jca>
Note that the org.switchyard.example.MyOperationSelectorImpl needs to be a subclass of org.switchyard.component.common.selector.OperationSelector or other concrete OperationSelector classes for each service bindings. You can override the selectOperation() method as you like.
Default OperationSelector implementation for each service bindings are following:
Camel : org.switchyard.component.camel.selector.CamelOperationSelector
JCA/JMS : org.switchyard.component.jca.selector.JMSOperationSelector
JCA/CCI : org.switchyard.component.jca.selector.CCIOperationSelector
HTTP : org.switchyard.component.http.selector.HttpOperationSelector
Support for operation selector is limited to Camel, JCA and HTTP service bindings. Support for other service bindings will be added in the future.
Transformation represents a change to the format and/or representation of a message's content. The representation of a message is simply the Java contract (e.g. java.lang.String, org.example.MyFancyObject) used to access the underlying content. The format of a message refers to the actual structure of the data itself. Examples of data formats include XML, JSON, CSV, and EDI.
Take the following message content:
<MyBook> <Chapter1> <Chapter2> </MyBook>
The format of this content is XML. One representation of XML in Java is as a String. Of course, the representation could also be a org.w3c.dom.Document, java.io.InputStream, etc.
String content = "<MyBook>...";
Transformation plays an important role in connecting service consumers and providers, since the format and representation of message content can be quite different between the two. For example, a SOAP gateway binding will likely use a different representation and format for messages than a service offered by a Java Bean. In order to route services from the SOAP gateway to the Bean providing the service, the format and representation of the SOAP message will need to change. Implementing the transformation logic directly in the consumer or provider pollutes the service logic and can lead to tight coupling. SwitchYard allows for the transformation logic to declared outside the service logic and injected into the mediation layer at runtime.
Transformation of message content is specified in the descriptor of your SwitchYard application (switchyard.xml). The qualified name of the type being transformed from as well as the type being transformed to are defined along with the transformer implementation. This allows transformation to be a declarative aspect of a SwitchYard application, as the runtime will automatically register and execute transfomers in the course of a message exchange.
<transforms> <transform.java bean="MyTransformerBean" from="{urn:switchyard-quickstart-demo:orders:1.0}submitOrder" to="java:org.switchyard.quickstarts.demos.orders.Order"/> </transforms>
Since transformations occur between named types (i.e. from type A, to type B), it's important to understand how the type names are derived. The type of the message is determined based on the service contract, which can be WSDL or Java.
For WSDL interfaces, the message name is determined based on the fully-qualified element name of a WSDL message. Take the following WSDL definition:
<definitions xmlns:tns="urn:switchyard-quickstart:bean-service:1.0"> <message name="submitOrder"> <part name="parameters" element="tns:submitOrder"/> </message> <portType name="OrderService"> <operation name="submitOrder"> <input message="tns:submitOrder"/> </operation> </portType> </definitions>
This would yield the following message type name based on the message element name defined in the WSDL:
{urn:switchyard-quickstart:bean-service:1.0}submitOrder
When Java interfaces are used for the service contract, the message name consists of the full package name + the class name, prefixed with "java:".
package org.switchyard.example; public interface OrderService { void submitOrder(Order order); }
The message type name for the submitOrder method in this Java interface would be "java:org.switchyard.example.Order". Occasionally, it can be useful to override the default operation name generated for a Java interface. The @OperationTypes annotation provides this capability by allowing the user to specify the input, output, and/or fault type names used for a Java service interface. For example, if we wanted to accept XML input content without any need for transformation to a Java object model, the OrderService interface could be changed to look like this:
package org.switchyard.example; @OperationTypes(in = "{urn:switchyard-quickstart:bean-service:1.0}submitOrder") public interface OrderService { void submitOrder(String orderXML); }
Aside from short-circuiting the requirement for transformation, this annotation can be useful if you want to maintain tight control over the names used for message content.
There are two methods available for creating a Java-based transformer in SwitchYard:
Implement the org.switchyard.transform.Transfomer interface and add a <transform.java> definition to your switchyard.xml.
Annotate one or more methods on your Java class with @Transformer.
When using the @Transformer annotation, the SwitchYard maven plugin will automatically generate the <transform.java> definition(s) for you and add them to the switchyard.xml packaged in your application. The following Java class would produce the <transform.java> definition provided above:
@Named("MyTransformerBean") public class MyTransformer { @Transformer(from = "{urn:switchyard-quickstart-demo:orders:1.0}submitOrder") public Order transform(Element from) { // handle transformation here } }
The optional from and to elements of the @Transformer annotation can be used to specify the qualified type name used during transformer registration. If not supplied, the full class name of the method parameter will be used as the from type and the full class name of the return type will be used as the to type.
The CDI bean name specified by @Named annotation is used to resolve transformer class. If you don't specify, then class name of the transformer is used instead like following:
<transforms> <transform.java class="org.switchyard.quickstarts.demos.orders.MyTransformer" from="{urn:switchyard-quickstart-demo:orders:1.0}submitOrder" to="java:org.switchyard.quickstarts.demos.orders.Order"/> </transforms>
Note that both of above <transform.java> definition has a bean attribute or a class attribute. bean attribute and class attribute are mutually exclusive.
There are three distinct transformation models available with Smooks in SwitchYard:
XML to Java : Based on a standard Smooks Java Binding configuration.
Java to XML: Based on a standard Smooks Java Binding configuration.
Smooks : This is a "normal" Smooks transformation in which the developer must define which Smooks filtering Result is to be exported back to the SwitchYard Message as the transformation result.
Smooks transformations are declared by including a <transform.smooks> definition in switchyard.xml.
<transform.smooks config="/smooks/OrderAck_XML.xml" from="java:org.switchyard.quickstarts.transform.smooks.OrderAck" to="{urn:switchyard-quickstart:transform-smooks:1.0}submitOrderResponse" type="JAVA2XML"/>
The config attribute points to a Smooks resource containing the mapping definition. The type attribute can be one of SMOOKS, XML2JAVA, or JAVA2XML.
The JSON transformer provides a basic mapping facility between POJOs and JSON (JSON marshalling and unmarshalling). Just like the JAXB Transformer, specification of the transformer requires a to and from specification with one Java type and one QNamed JSON type, depending on whether you're performing a Java to JSON or JSON to Java transformation.
The following configuration illustrates a JSON to Java transformation.
<trfm:transform.json from="{urn:switchyard-quickstart:transform-json:1.0}order" to="java:org.switchyard.quickstarts.transform.json.Order"/>
The following configuration illustrates a Java to JSON transformation of the same types as above.
<trfm:transform.json from="java:org.switchyard.quickstarts.transform.json.Order" to="{urn:switchyard-quickstart:transform-json:1.0}order"/>
The XSLT transformer allows you to perform a transformation between 2 types, using an XSLT. It is configured simply by specifying the to and from QNames, as well as the path to the XSLT to be applied.
<transform.xslt from="{http://acme/}A" to="{http://acme/}B" xsltFile="com/acme/xslt/A2B.xslt"/>
The JAXB transformer allows you to perform Java to XML (and XML to Java) transformations using JAXB (XML marshalling and unmarshalling). It is exactly like the JSON Transformer in terms of how it is configured i.e. a to and from configuration with one Java type and one QNamed XML type.
JAXB Java models can be generated from an XML Schema using XJC, or from a WSDL using tools like wsconsume (.sh/.bat), which is shipped with both SwitchYard AS6 and AS7 distros (in the bin directory).
Working out the available transformations is quite simple. Just look in the ObjectFactory class source file (ObjectFactory.java). In this source file you will see factory methods representing the available marshallings/unmarshallings e.g.
@XmlElementDecl(namespace = "http://com.acme/orders", name = "create") public JAXBElement<CreateOrder> createOrder(CreateOrder value) { return new JAXBElement<Order>(_CreateOrder_QNAME, CreateOrder.class, null, value); }
In the above example, the @XmlElementDecl annotation tells us that the XML QName associated with the com.acme.orders.CreateOrder type is "{http://com.acme/orders}create". From this, we can deduce that we have the following possible SwitchYard JAXB Transformer configurations:
<transform.jaxb from="{http://com.acme/orders}create" to="java:com.acme.orders.CreateOrder" /> <transform.jaxb from="java:com.acme.orders.CreateOrder" to="{http://com.acme/orders}create" />
One of the nice things about the JAXB Transformer integrations in SwitchYard is the fact that JAXB Transformations are automatically detected and automatically added, for your application deployment. So, if for example, you develop a CDI Bean Service and use JAXB generated types in the Service Interface, you will not need to configure any of the transformations. SwitchYard will automatically detect their availability for your application and will automatically apply them at the appropriate time during service invocation.
Validation feature provides a functionality for message content validation.
Take the following message content:
<MyBook xmlns="example"> <Chapter1/> <Chapter2/> </MyBook>
And follwing XML Schema definition:
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="example" xmlns:orders="example"> <element name="MyBook" type="example:MyBook"/> <complexType name="MyBook"> <sequence> <element name="Chapter1" type="string"/> </sequence> </complexType> </schema>
The XML content is still Well-Formed, but it has a Chapter2 element that is not declared as the child of MyBook element in the XML Schema, So the content is not Valid against this XML Schema. We often need to perform this kind of validation before processing its data in service logic, but implementing the validation logic directly in the consumer or provider pollutes the service logic and can lead to tight coupling. SwitchYard allows for the validation logic to declared outside the service logic and injected into the mediation layer at runtime.
Validation of message content is specified in the descriptor of your SwitchYard application (switchyard.xml). The qualified name of the type being validated name is defined along with the validator implementation. This allows validation to be a declarative aspect of a SwitchYard application, as the runtime will automatically register and execute validators in the course of a message exchange.
<validates> <validate.xml schemaType="XML_SCHEMA" name="{urn:example}MyBook"> <schemaFiles><entry file="/xsd/orders.xsd"/></schemaFiles> </validate.xml> </validates>
Since validations occur with named type (i.e. type A) as well as transformations, it's important to understand how the type names are derived. Please refer to the Content Type Names section in the Transformation chapter if you have not ever seen it.
There are two methods available for creating a Java-based validator in SwitchYard:
Implement the org.switchyard.validate.Validator interface and add a <validate.java> definition to your switchyard.xml.
Annotate one or more methods on your Java class with @Validator.
When using the @Validator annotation, the SwitchYard maven plugin will automatically generate the <validate.java> definition(s) for you and add them to the switchyard.xml packaged in your application.
@Named("MyValidatorBean") public class MyValidator { @Validator(name = "{urn:switchyard-quickstart-demo:orders:1.0}submitOrder") public ValidationResult validate(Element from) { // handle validation here } }
The above Java class would produce the <validate.java> definition as following:
<validate.java bean="MyValidatorBean" name="{urn:switchyard-quickstart-demo:orders:1.0}submitOrder"/>
The optional name element of the @Validator annotation can be used to specify the qualified type name used during validator registration. If not supplied, the full class name of the method parameter will be used as the type.
The CDI bean name specified by @Named annotation is used to resolve validator class. If you don't specify, then class name of the validator is used instead like following:
<validates> <validate.java class="org.switchyard.quickstarts.demos.orders.MyValidator" name="{urn:switchyard-quickstart-demo:orders:1.0}submitOrder"/> </transforms>
Note that both of above <validate.java> definition has a bean attribute or a class attribute. bean attribute and class attribute are mutually exclusive.
ValidationResult is a simple interface which represents the result of validation. It has 2 methods, isValid() and getDetail(). isValid() returns whether the validation succeeded or not. _getDetail() returns error message if validation failed.
package org.switchyard.validate; public interface ValidationResult { boolean isValid(); String getDetail(); }
There are 3 convenience methods on org.switchyard.validate.BaseValidator, validResult(), invalidResult(), and invalidResult(String) which help you to generate ValidationResult object.
The XML validator allows you to perform a validation against its schema definition. Supported schema types are DTD, XML_SCHEMA, and RELAX_NG. It is configured simply by specifying the schema Type, the name QName, and the path to the schema file.
<validate.xml schemaType="XML_SCHEMA" name="{urn:switchyard-quickstart:validate-xml:0.1.0}order" failOnWarning="true" namespaceAware="true"> <schemaFiles> <entry file="/xsd/orders.xsd"/> </schemaFiles> <schemaCatalogs> <entry file="/xsd/catalog.xml"/> </schemaCatalogs> </validate.xml>
If you specify failOnWarning attribute as true, then validation would fail if any warning is detected during validation. If the XML content to be validated has namespace prefix, then you need to specify namespaceAware as true.
You can use XML catalog to decouple the schema file location from schema definition itself. This schema is orders.xsd which has a import element. It refers to logical name orders.base by the schemaLocation attribute:
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:switchyard-quickstart:validate-xml:0.1.0" xmlns:base="urn:switchyard-quickstart:validate-xml-base:0.1.0" xmlns:orders="urn:switchyard-quickstart:validate-xml:0.1.0"> <import namespace="urn:switchyard-quickstart:validate-xml-base:0.1.0" schemaLocation="orders.base"/> ...
And this is the catalog.xml which resolves actual schema location from logical name orders.base:
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"> <system systemId="orders.base" uri="orders-base.xsd"/> </catalog>
Testing your applications is dead simple with the comprehensive unit test support provided in SwitchYard. There are three primary elements to test support in SwitchYard:
SwitchYardRunner: JUnit test Runner class which takes care of bootstrapping an embedded SwitchYard runtime and deploying a SwitchYard application for the test instance. Its behavior is influenced heavily by the optional SwitchYardTestCaseConfig annotation. Its runtime state is represented by the SwitchYardTestKit.
SwitchYardTestKit: represents the runtime state of the deployed SwitchYard application instance deployed by SwitchYardRunner. Also provides access to a set of test utility methods for the test (e.g. assertion methods). The SwitchYardTestKit is reflectively injected into the test instance, if a property of type SwitchYardTestKit is declared in the test.
SwitchYardTestCaseConfig: optional annotation allows additional information to be specified for controlling the behavior of the SwitchYardRunner.
Adding test support to your SwitchYard application is simply a matter of adding a dependency to the switchyard-test module in your application's pom.xml.
<dependency> <groupId>org.switchyard</groupId> <artifactId>switchyard-test</artifactId> <version>[release-version]</version> <!-- e.g. "0.7.0" --> <scope>test</scope> </dependency>
In addition to a dependency on the core test framework, you might want to take advantage of MixIns in your test classes. Dependency information for each MixIn is listed under the Test MixIns section.
To take advantage of the test support in SwitchYard, your unit test should be annotated with the SwitchYardRunner JUnit test Runner class. SwitchYardRunner takes care of creating and starting an embedded runtime for each test method. After the embedded runtime is started, the project containing the test is packaged as a SwitchYard application and deployed to it. The runtime state of the deployed SwitchYard test application is represented by an instance of the SwitchYardTestKit class, which is injected into the test when a property of type SwitchYardTestKit is declared in the test.
@RunWith(SwitchYardRunner.class) public class MyServiceTest { private SwitchYardTestKit testKit; @Test public void testOperation() { MyTestServiceHandler service = new MyTestServiceHandler(); // register the service... testKit.registerInOutService("MyService", service); // invoke the service and capture the response... Message response = newInvoker("MyService") .sendInOut("<create>A1234</create>"); // test the response content by doing an XML comparison with a // file resource on the classpath... testKit.compareXMLToResource(response.getContent(String.class), "/myservice/expected-create-response.xml"); } private class MyTestServiceHandler implements ExchangeHandler { // implement methods.... } }
The SwitchYardTestKit provides a set of utility methods for performing all sorts of deployment configuration and test operations.
The optional SwitchYardTestCaseConfig annotation can be used control the behavior of the SwitchYardRunner:
config: allows the specification of a SwitchYard XML configuration file (switchyard.xml) for the test. The SwitchYardRunner will attempt to load the specified configuration from the classpath. If if fails to locate the config on the classpath, it will then attempt to locate it on the file system (e.g. within the project structure).
mixins: composition-based method for adding specific testing tools to your test case. Each TestMixIn provides customized testing tools for things like service implementations, gateway bindings, and transformers. When a TestMixIn is annotated on a Test Class, the SwitchYardRunner handles all the initialization and cleanup (lifecycle) of the TestMixIn instance(s). It's also possible to manually create and manage TestMixIn instance(s) within your test class if (for example) you are not using the SwitchYardRunner.
scanners: add classpath scanning as part of the test lifecycle. This adds the same Scanner behavior as is available with the SwitchYard maven build plugin, but allows the scanning to take place as part of the test lifecycle. You will often find that you need to add Scanners if you want your test to run inside your IDE. This is because running your test inside your IDE bypasses the whole maven build process, which means the build plugin does not perform any scanning for you.
@RunWith(SwitchYardRunner.class) @SwitchYardTestCaseConfig(config = "testconfigs/switchyard-01.xml", mixins = {CDIMixIn.class, BPMMixIn.class}, scanners = {BeanSwitchYardScanner.class, TransformSwitchYardScanner.class}) public class MyServiceTest { @Test public void testOperation() { newInvoker("OrderService") .operation("createOrder") .sendInOnly("<order><product>AAA</product><quantity>2</quantity></order>"); } }
The TestMixIn feature allows you to selectively enable additional test functionality based on the capabilities of your application. To include MixIn support in your application, you must include a Maven dependency in your application's pom.xml.
<dependency> <groupId>org.switchyard.components</groupId> <artifactId>switchyard-component-test-mixin-name</artifactId> <version>release-version</version> <!-- e.g. "0.7.0" --> <scope>test</scope> </dependency>
CDIMixIn (switchyard-component-test-mixin-cdi) : boostraps a stand-alone CDI environment, automatically discovers CDI beans, registers bean services, and injects references to SwitchYard services.
HTTPMixIn (switchyard-component-test-mixin-http) : client methods for testing HTTP-based services.
SmooksMixIn (switchyard-component-test-mixin-smooks) : stand-alone testing of any Smoooks transformers in your application.
BPMMixIn (switchyard-component-test-mixin-bpm) : utility methods for working with jBPM 5 Human Tasks (like starting/stopping a TaskServer).
HornetQMixIn (switchyard-component-test-mixin-hornetq) : bootstraps a stand-alone HornetQ server and provides utility methods to interact with it for testing purpose. It can be also used to interact with remote HornetQ server.
JCAMixIn (switchyard-component-test-mixin-jca) : bootstraps a embedded IronJacamar JCA container and provides utility methods to interact with it for testing purpose. It has a MockResourceAdapter feature to simulate the SwitchYard application behavior without connecting to the real EIS systems.
NamingMixIn (switchyard-component-test-mixin-naming) : provides access to naming and JNDI services within an application.
PropertyMixIn (switchyard-test) : provides ability to set test values to properties that are used within the configuration of the application.
Scanners add classpath scanning as part of the test lifecycle. This adds the same Scanner behavior as is available with the SwitchYard maven build plugin, but allows the scanning to take place as part of the test lifecycle. The following Scanners are available:
BeanSwitchYardScanner: Scans for CDI Bean Service implementations.
TransformSwitchYardScanner: Scans for Transformers.
BpmSwitchYardScanner: Scans for @Process, @StartProcess, @SignalEvent and @AbortProcessInstance annotations.
RouteScanner: Scans for Camel Routes.
RulesSwitchYardScanner: Scans for @Rule annotations.
As shown above, injecting the SwitchYardTestKit instance into the test at runtime is simply a case of declaring a property of that type in the test class.
@RunWith(SwitchYardRunner.class) public class MyServiceTest { private SwitchYardTestKit testKit; // implement test methods... }
The SwitchYard test framework also injects other test support and metadata classes, which we outline in the following sections.
The Deployment instance can be injected by declaring a property of type Deployment.
@RunWith(SwitchYardRunner.class) public class MyServiceTest { private Deployment deployment; // implement test methods... }
The SwitchYardModel instance can be injected by declaring a property of type SwitchYardModel.
@RunWith(SwitchYardRunner.class) public class MyServiceTest { private SwitchYardModel model; // implement test methods... }
The ServiceDomain instance can be injected by declaring a property of type ServiceDomain.
@RunWith(SwitchYardRunner.class) public class MyServiceTest { private ServiceDomain serviceDomain; // implement test methods... }
The TransformerRegistry instance can be injected by declaring a property of type TransformerRegistry.
@RunWith(SwitchYardRunner.class) public class MyServiceTest { private TransformerRegistry transformRegistry; // implement test methods... }
TestMixIn instance(s) can be injected by declaring properties of the specific type TestMixIn type.
@RunWith(SwitchYardRunner.class) @SwitchYardTestCaseConfig(mixins = {CDIMixIn.class, HTTPMixIn.class}) public class MyServiceTest { private CDIMixIn cdiMixIn; private HTTPMixIn httpIn; // implement test methods... }
PropertyMixIn instance(s) are injected like any other TestMixIn type, however any properties you set on the mix in have to be done before deployment to be respected, thus the use of the @BeforeDeploy annotation:
@RunWith(SwitchYardRunner.class) @SwitchYardTestCaseConfig(mixins = {CDIMixIn.class, PropertyMixIn.class, HTTPMixIn.class}) public class MyServiceTest { private PropertyMixIn propMixIn; private HTTPMixIn httpMixIn; @BeforeDeploy public void setTestProperties() { propMixIn.set("soapPort", Integer.valueOf(18002)); } // implement test methods... }
Service Invoker instance(s) can be injected by declaring properties of type Invoker and annotating them with @ServiceOperation annotation.
@RunWith(SwitchYardRunner.class) @SwitchYardTestCaseConfig(config = "testconfigs/switchyard-01.xml") public class MyServiceTest { @ServiceOperation("OrderService.createOrder") private Invoker createOrderInvoker; @Test public void test_createOrder() { createOrderInvoker.sendInOnly("<order><product>AAA</product><quantity>2</quantity></order>"); } }
Note the annotation value is a dot-delimited Service Operation name of the form "service-name.operation-name".
The test framework defaults to a mode where the entire application descriptor is processed during a test run. This means all gateway bindings and service implementations are activated during each test. There are times when this may not be appropriate, so we allow activators to be selectively enabled or disabled based on your test configuration.
The following example excludes SOAP bindings from all tests. This means that SOAP gateway bindings will not be activated when the test framework loads the application.
@RunWith(SwitchYardRunner.class) @SwitchYardTestCaseConfig(config = "testconfigs/switchyard-01.xml" exclude="soap") public class NoSOAPTest { ... }
This example includes only CDI bean services defined in the application descriptor.
@RunWith(SwitchYardRunner.class) @SwitchYardTestCaseConfig(config = "testconfigs/switchyard-02.xml" include="bean") public class BeanServicesOnlyTest { ... }
Sometimes we need to add some procedures before test is performed. JUnit @Before operation is invoked right after the application is deployed, however, it can't be used if you expect something before deploy. We have @BeforeDeploy annotation for this purpose. This is required to test the application which has JCA binding with using JCAMixIn since the ResourceAdapter must be deployed before the application is activated.
This is the example for deploying HornetQ ResourceAdapter to the embedded IronJacamar JCA Container using JCAMixIn.
@BeforeDeploy public void before() { ResourceAdapterConfig ra = new ResourceAdapterConfig(ResourceAdapterConfig.ResourceAdapterType.HORNETQ); _jcaMixIn.deployResourceAdapters(ra); }
Since 0.6 release SwitchYard supports basic audit mechanism. The Auditing stuff require CDI environment to run, in other words META-INF/beans.xml is necessary. It's worth to note that auditing stuff works also in test environment.
SwitchYard exchange sent from service consumer to service provider goes trough few states. Depends on state you might have different message payload and different metadata on exchange:
Domain handlers - it's a place where all handlers defined in switchyard.xml are executed, it's early phase of mediation where you can implement own logic or chose service provider using own logic.
Addressing - if none from domain handlers specified providing service then addressing handler determines it using consumer contract.
Transaction - when service requires transaction this handler starts it
Security - verifies contraints related to authentication and authorization
General policy - executes other checks different than security and transaction
Validation - executes custom validators
Transformation - prepare payload for calling providing service
Validation - validates transformed payload
Provider call - calls providing service
Transaction - commits or rollbacks transaction, if necessary
If service consumer is synchronous and exchange pattern is set to in-out then some from these handlers are called once again:
Domain handlers - called with response generated by provider service
Validation - verifies output generated by provider
Transformation - converts payload to structure required by consumer
Validation - checks output after transformation
Consumer callback - returns exchange to service consumer
As said before audit mechanism requires CDI runtime to work. Annotate your Auditor implementations with the @Named annotation in order to have Camel recognise them. Camel Exchange Bus (a default implementation used by SwitchYard) look up for bean definitions with @Audit annotation. Simplest auditor looks following:
@Audit @Named("custom auditor") public class SimpleAuditor implements Auditor { @Override public void beforeCall(Processors processor, Exchange exchange) { System.out.println("Before " + processor.name()); } @Override public void afterCall(Processors processor, Exchange exchange) { System.out.println("After " + processor.name()); } }
You will see lots of statements printed in server console like 'Before DOMAIN_HANDLERS', 'Before ADDRESSING' and so on. Every step of mediation is surrounded by this SimpleAuditor class.
Be aware that afterCall method is not called if surrounded step thrown an exception. In this case call of afterCall is skipped.
If you are not interested in all these states of SwitchYard mediation process you might provide argument to @Audit annotation. Accepted values must come from org.switchyard.bus.camel.processors.Processors enumeration. For example @Audit(Processors.VALIDATION) will handle only validation occurances.
Please remember that validation is executed twice for in-only exchanges and fourth times for in-out. Validation occurs before transformation of inbound message and after transformation. In case when outgoing message will be sent from SwitchYard service validation is executed before transformation of outbound message and after transformation.
Transformation is executed once for in-only exchanges and twice for in-out exchanges.
Transaction phase is always executed twice.
If you are interested in only one execution of your auditor use following combination @Audit(Processors.PROVIDER_CALLBACK). Auditor will be executed just before sending exchange to service implementation. It's also possible to stick one auditor instance with few mediation steps. For example bean with annotation @Audit({Processors.PROVIDER_CALLBACK, Processors.CONSUMER_CALLBACK}) will be executed twice. One pair of before/after call for provider service and second pair for outgoing response.
Custom auditors should not preserve state inside any fields because dispatching order is not guaranteed and only one instance of auditor is created by default. If you would like store some values please use exchange properties or message headers. Example below shows how to count processing time using Exchange properties as temporary storage.
@Named("custom auditor") public class SimpleAuditor implements Auditor { private Logger _logger = Logger.getLogger(SimpleAuditor.class); @Override public void beforeCall(Processors processor, Exchange exchange) { exchange.setProperty("time", System.currentTimeMillis()); } @Override public void afterCall(Processors processor, Exchange exchange) { long time = System.currentTimeMillis() - exchange.getProperty("time", 0, Long.class); _logger.info("Step " + processor.name() + " took " + time + "ms"); } }
The RemoteInvoker serves as a remote invocation client for SwitchYard services. It allows non-SwitchYard applications to invoke any service in SwitchYard which uses a <binding.sca> binding. It is also used by the internal clustering channel to facilitate intra-cluster communication between instances.
RemoteInvoker and supporting classes can be included in your application via the following Maven dependency:
<dependency> <groupId>org.switchyard</groupId> <artifactId>switchyard-remote</artifactId> <version> <!-- SY version goes here (e.g. 0.8.0.Final) --> </version> </dependency>
Each instance of SY includes a special context path called "switchyard-remote" which is bound to the default HTTP listener in AS 7. The initial version of RemoteInvoker supports communication with this endpoint directly. Here's an example of invoking an in-out service in SY using the HttpInvoker:
public class MyClient { public static void main(String[] args) throws Exception { RemoteInvoker invoker = new HttpInvoker("http://localhost:8080/switchyard-remote"); Offer offer = new Offer(); offer.setAmount(100); offer.setItem("honda"); RemoteMessage msg = invoker.invoke(new RemoteMessage() .setContext(new DefaultContext()) .setService(new QName("urn:com.example.switchyard:remote", "Dealer")) .setContent(offer)); Deal deal = (Deal)msg.getContent(); System.out.println("It's a deal? " + deal.isAccepted()); } }
The remote-invoker quickstart serves as a nice example of using RemoteInvoker with a SwitchYard application.
Serialization becomes a concern within SwitchYard with regards to clustering and execution from a client invoker (introduced in 0.6.0.Beta2). In those cases, objects that represent the content of a SwitchYard Message or objects that are placed within a SwitchYard Exchange's Context become candidates for serialization/deserialization.
Custom (application-defined) objects that are stored as the content of the message or property of the exchange context are not required to implement java.io.Serializable. This is because SwitchYard does not use the JDK's default object serialization mechanism. Rather, it traverses the object graph, extracting the properties along the way, and stores the values in it's own graph representation, which by default is serialized to/from the JSON format. This is what ends up going over the wire. For this to work, custom objects must follow one of the following two rules:
Adhere to the JavaBeans specification. This means a public, no arg constructor, and public getter/setter pairs for every property you want serialized. If you go this (suggested) route, your custom objects will not require any compilation dependencies on SwitchYard.
Use SwitchYard annotations to define your serialization strategy (see below).
The following annotations, enums, interface and class exist in the org.switchyard.serial.graph package:
@Strategy - Here you can define the serialization strategy, including access type, coverage type, and factory (all optional) for your class.
access=AccessType - BEAN (default) for getter/setter property access, FIELD for member variable access.
coverage=CoverageType - INCLUSIVE (default) for serializing all properties, EXCLUSIVE for ignoring all properties. (See @Include and @Exclude below for overrides.)
factory=Factory - Interface for how the class gets instantiated.
DefaultFactory - Creates an instance of the class using the default constructor.
@Include - Placed on individual getter methods or fields to override CoverageType.EXCLUSIVE.
@Exclude - Placed on individual getter methods or fields to override CoverageType.INCLUSIVE.
As an application developer, you should not have to use SwitchYard's serialization API directly. However, documentation is still presented here.
Serialization is done using Serializers, obtained from the SerializerFactory. For example:
// See SerializerFactory for overloaded "create" methods. Serializer ser = SerializerFactory.create(FormatType.JSON, CompressionType.GZIP, true); // to and from a byte array Foo fooBefore = new Foo(); byte[] bytes = ser.serialize(fooBefore, Foo.class); Foo fooAfter = ser.deserialize(bytes, Foo.class); // to and from output/input streams Bar barBefore = new Bar(); OutputStream out = ... ser.serialize(barBefore, Bar.class, out); InputStream in = ... Bar barAfter = ser.deserialize(in, Bar.class);
Out of the box, the available FormatTypes are SER_OBJECT, XML_BEAN and JSON, and the available CompressionTypes are GZIP, ZIP, or null (for no compression).
In the example Serializer.create invocation above, the 3rd (boolean) argument means that the object graph will be walked via reflection, as per the description in "Application-Defined Objects" above.